Hi @Jonathan ,
Yes, you can do both in the same query: first exclude the unwanted lines with Where(), then extract the part you need with Select().
For example, suppose each line in the file contains a name, an IP address, and a status:
John,192.168.1.10,Active
Alice,192.168.1.20,Inactive
Test,192.168.1.30,Active
Bob,192.168.1.40,Active
To exclude the lines for John and Test, and keep only the IP address from the middle of each remaining line:
var path = @"c:/tmp/list11.txt";
var excludedNames = new HashSet<string>(
new[] { "John", "Test" }, StringComparer.OrdinalIgnoreCase);
var ipSet = new HashSet<string>(
File.Exists(path)
? File.ReadLines(path)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => line.Split(','))
.Where(parts => parts.Length >= 3) // skip malformed lines
.Where(parts => !excludedNames.Contains(parts[0].Trim())) // exclude by name
.Select(parts => parts[1].Trim()) // take the IP field
: Enumerable.Empty<string>(),
StringComparer.OrdinalIgnoreCase
);
Result:
192.168.1.20
192.168.1.40
If the excluded strings can appear anywhere in the line, not just in a specific field, you can check the whole line instead:
.Where(line => !excludedNames.Any(name =>
line.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0))
Note that this is a partial match. For example, John would also exclude a line containing Johnson. That's why comparing a specific field, as in the first example, is usually more accurate.
If your lines don't use a delimiter, you can use IndexOf() and Substring() to take the text between two markers. For example, from Name=Bob; IP=192.168.1.40; Status=Active:
.Select(line =>
{
int start = line.IndexOf("IP=");
if (start < 0) return null;
start += 3;
int end = line.IndexOf(';', start);
return end < 0 ? line.Substring(start) : line.Substring(start, end - start);
})
.Where(ip => ip != null)
If you found my response helpful or informative, I would greatly appreciate it if you could follow this guide for your confirmation
Thank you.