0

I have a string array with fixed values and a richtextbox whose text is dynamically changed. Some of the lines in the richtextbox start with values in the string array. I want to select only the lines of the richtextbox which do not start with values in the string array. The following code returns all lines in the richtextbox.

string[] parts = new string[] { "Definition:", "derivation:", "derivations:"};
IEnumerable<string> lines = richTextBox1.Lines.Where(
c =>parts.Any(b=>!c.StartsWith(b)));

My question is: How can I select only the lines of the richtextbox which do not start with values in the string array?

0

2 Answers 2

8

Change Any to All. As it's written, it returns all lines because a line can't start with more than one word.

Your current code says, "return true if there is any word in parts that isn't the first word of the line." Obviously, the line can't start with "foo" and with "derivation:". So you always get true.

You want to say, "return true if all of the words in parts are not the first word of the line."

Another way to do it is:

lines = richTextBox1.Lines.Where(c => !parts.Any(b => c.StartsWith(b)));

Which is probably how I would have written it.

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

4 Comments

I changed Any to All, still I got all lines. Thanks anyway.
@FadelMS: Not sure what you did, but changing Any to All in your code cannot possibly return the same thing. Unless none of the lines in your text box starts with any of the words in parts. I tested your code against an array of strings; it returned everything. Changing Any to All returned the expected results.
Sorry Jim, the problem was with the position of the operator '!'. Thanks
@FadelMS: Yes, as I pointed out in my other way to do it. My original point stands, though. !Any(x == y) is the same as All(x != y). That is, changing Any to All should work.
3

You put the (!) operator in the wrong place. If you want to use Any then

string[] parts = new string[] { "Definition:", "derivation:", "derivations:"};
IEnumerable<string> lines = richTextBox1.Lines.Where(
                                 c => !parts.Any(b => c.StartsWith(b)));

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.