Issue to Hash set

Jonathan 420 Reputation points
2026-10-02T09:18:04.3833333+00:00

Hi,

To the codes similar to the following, can I put the conditions and also to extract a substring from one given text file?

User's image

Developer technologies | C#
Developer technologies | C#

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.

0 comments No comments

3 answers

Sort by: Oldest
  1. Harry Nguyen (WICLOUD CORPORATION) 180 Reputation points Microsoft External Staff Moderator
    2026-10-02T09:55:08.6466667+00:00

    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.

    Was this answer helpful?

    2 people found this answer helpful.

  2. Harry Nguyen (WICLOUD CORPORATION) 180 Reputation points Microsoft External Staff Moderator
    2026-10-02T10:32:03.2033333+00:00

    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.

    Was this answer helpful?

    1 person found this answer helpful.

  3. Senthil kumar 2,585 Reputation points
    2026-10-05T04:53:44.2733333+00:00

    Hi @Jonathan

    Yes, absolutely. The code in your screenshot creates a HashSet<string> from a text file. You can add conditions, filtering, and substring extraction while reading the file.

    For example, if you want to:

    • Read all lines
    • Trim spaces
    • Ignore empty lines
    • Only include lines that start with "IP:"
    • Extract a portion of the string
    IP:10.1.1.1
    IP:10.1.1.2
    IP:10.1.1.3
    
    var ipSet = new HashSet<string>(
     File.ReadLines(@"c:\cmp\list11.txt")
     .Select(l => l.Trim())
     .Where(l => l.StartsWith("IP:"))
     .Select(l => l.Substring(3)),
     StringComparer.OrdinalIgnoreCase
    );
    
    
    

    filter based on length:

    var ipSet = new HashSet<string>(
     File.ReadLines(@"c:\cmp\list11.txt")
     .Select(l => l.Trim())
     .Where(l => l.Length > 10)
     .Select(l => l.Substring(0, 10)),
     StringComparer.OrdinalIgnoreCase
    );
    

    Thanks.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.