Home > OS >  LINQ query to parse List and get multiple groups based on the initial character
LINQ query to parse List and get multiple groups based on the initial character

Time:01-24

Greeting Gurus, I have a LINQ query that parses a text file.

var p = from n in File.ReadAllLines(@"D:\data.txt")
                            where n.StartsWith("-"||"/")
select n;

I'm getting an error about the or operator || cannot be applied to strings?! I'm trying to get groups of lines that start with different switches (a group for / and a group for -.

CodePudding user response:

You want this:

IEnumerable<string> p =
    from n in File.ReadAllLines(@"D:\data.txt")
    where n.StartsWith("-") || n.StartsWith("/")
    select n;

If you want to also group by the first character, then try this:

IEnumerable<IGrouping<char, string>> p =
    from n in File.ReadAllLines(@"D:\data.txt")
    where n.Length > 1
    let k = n[0]
    where k == '-' || k == '/'
    group n by k;

Perhaps you need this:

ILookup<char, string> p =
    File
        .ReadAllLines(@"D:\data.txt")
        .Where(n => n.Length > 1 && (n[0] == '-' || n[0] == '/'))
        .ToLookup(n => n[0], x => x);
    
IEnumerable<string> startsWithHyphen = p['-'];
IEnumerable<string> startsWithSlash = p['/'];
  •  Tags:  
  • Related