Add AND and OR to Where de list

Asked

Viewed 78 times

1

I have a list on C# and currently the search code is like this:

filter = lst.Where(s => s.Contains(num.Text) ).Take(3).ToList();

The list lst is based on a list with phone numbers and contact names, example:

123456789$nome1

987654321$nome2

Currently I am looking for the number, I wanted to do an OR to be able to search also by the name example:

num.Text = 9;
nome.Text = "l";

I wanted to get the first 3 items on the list that has the value of nome.Text OR OF num.Text

  • 1

    Any specific difficulty? It is equal to an if`` .

  • To lst has fields of type Numeric or Text?

  • It has been a long time that I do not touch with C#, today I went to add this functionality and do not remember anything of the method Where, his condition would be if s contains num.Text or nome.Text

  • This is a list of string

2 answers

4

You can do it like a if:

filter = lst.Where(s => s.Contains(num.Text) || s.Contains(nome.Text)).Take(3).ToList();

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

This will do for all items in the list. Item by item, one at a time. First you look for a criterion, if you find it, great, if you don’t find it, he searches for the second criterion, if he finds it, he returns true and will advance to the Take(3). When he gets to the third item he’s given true he does not look for anything else. And this is one of the beauties of LINQ, he does not waste time with what he no longer needs (helped in this case by the mechanism of short-Circuit of relational operators.

Eventually optimizations can be made, but I doubt it will be necessary in most cases

3


Use the operator or || inside your Where.

filter = lst.Where(s => s.Contains(num.Text) || s.Contains(nome.Text) ).Take(3).ToList();

Here’s an example I did on Dotnet Fiddle https://dotnetfiddle.net/EYC2gF

Browser other questions tagged

You are not signed in. Login or sign up in order to post.