FadelMS
FadelMS

Reputation: 2037

Comparing string array with starting values in another

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?

Upvotes: 0

Views: 191

Answers (2)

Esteban Elverdin
Esteban Elverdin

Reputation: 3582

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)));

Upvotes: 3

Jim Mischel
Jim Mischel

Reputation: 134125

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.

Upvotes: 8

Related Questions