Freud
Freud

Reputation: 15

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?

Upvotes: 0

Views: 542

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26675

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.

Upvotes: 8

Related Questions