Search code examples
c#stringlinqstartswithsub-array

C# subarray of strings with LINQ


I have an array of strings and I have to take only those entries, which are starting with "81" or "82". I've tried it like this:

var lines = File.ReadAllLines(fileName); // This returns an array of strings
lines = lines.TakeWhile(item => item.StartsWith("81") ||item.StartsWith("82")).ToArray();

but this just doesn't work. It retuns an empty string array.

When I loop through lines with a for-loop and compare everytime

if (!firstline.Substring(0, 2).StartsWith("81")) continue;

and then I take the required entries, it's working just fine.

Any suggestions how to get it right with LINQ?


Solution

  • You need to use Where():

    lines = lines.Where(item => item.StartsWith("81") || item.StartsWith("82")).ToArray();
    

    TakeWhile will take sequence until condition becomes false, but Where will continue and find all elements matching the condition.