An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Hi @Jonathan ,
Yes, you can add conditions while reading the file and also extract only the part of each line that you need before storing it in the HashSet.
Since File.ReadLines() returns each line as a string, you can use Where to filter the lines and Select to transform or extract values from them.
For example, some common conditions are:
// Contains specific text
.Where(line => line.Contains("Active"))
// Starts or ends with specific text
.Where(line => line.StartsWith("192.168."))
.Where(line => line.EndsWith(",Active"))
// Ignore empty lines
.Where(line => !string.IsNullOrWhiteSpace(line))
If a value represents a number, you can also parse it and apply a numeric condition. For example:
.Where(line => int.TryParse(line, out int value) && value > 100)
For substring extraction, the method depends on the structure of each line. For example, suppose the file contains:
192.168.1.10,Active
192.168.1.20,Inactive
192.168.1.30,Active
If the goal is to keep only the IP address from the Active lines, you could write:
var ipSet = new HashSet<string>(
File.Exists(@"c:/tmp/list11.txt")
? File.ReadLines(@"c:/tmp/list11.txt")
.Select(line => line.Trim())
.Where(line => line.EndsWith(",Active"))
.Select(line => line.Split(',')[0])
: Enumerable.Empty<string>(),
StringComparer.OrdinalIgnoreCase
);
In this example:
- Trim() removes leading and trailing whitespace.
- Where() determines which lines should be included.
- Split(',')[0] extracts the part before the comma.
- HashSet<string> keeps the resulting string values as a set, using the comparer you specified.
The resulting values would be:
192.168.1.10
192.168.1.30
If your file contains a different structure, you can change the condition in Where() and the extraction logic in Select(). If you provide one or two actual lines from the file and the expected result, we can adapt the example to match your data.
If you found my response helpful or informative, I would greatly appreciate it if you could follow this guide for your confirmation
Thank you.