Add AND and OR to Where de list

1

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

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

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

123456789$nome1

987654321$nome2

I'm currently searching for the number, I wanted to do an OR so I could search for the example name as well:

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

I wanted to get the first 3 items in the list that have the value of nome.Text OR num.Text

    
asked by anonymous 13.06.2016 / 20:53

2 answers

2

Use the or || operator within your where.

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

Here's an example I made in DotNet Fiddle link

    
13.06.2016 / 21:04
2

Can make equal to if :

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

This will do for all items in the list. Item by item, one at a time. First it looks for a criterion, if it finds, great, if it does not find it, it searches the second criterion, if it finds it it will return true and advance to Take(3) . When he reaches the third item that gave true he does not look for anything else. And this is one of LINQ's beauties, it does not waste time on what it does not need anymore (aided in this case by the short-circuit mechanism of relational operators.

Optimizations may be possible, but I doubt it is necessary in most cases

    
13.06.2016 / 21:07