0

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?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.