Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter in linq with ID's in a List<int>

I need do a filter that request data with a parameter included in a list.

if (filter.Sc.Count > 0)
    socios.Where(s => filter.Sc.Contains(s.ScID));

I try on this way but this not work, I tried also...

socios.Where( s => filter.Sc.All(f => f == s.ScID));

How I can do a filter like this?

like image 341
Maske Avatar asked Feb 12 '15 13:02

Maske


2 Answers

socios.Where(s => filter.Sc.Contains(s.ScID));

returns a filtered query. It does not modify the query. You are ignoring the returned value. You need something like:

socios = socios.Where(s => filter.Sc.Contains(s.ScID));

but depending on the type of socios the exact syntax may be different.

like image 75
D Stanley Avatar answered Sep 17 '22 00:09

D Stanley


In addition to needing to use the return value of your LINQ .Where(), you have a potential logic error in your second statement. The equivalent logic for a .Contains() is checking if Any of the elements pass the match criteria. In your case, the second statement would be

var filteredSocios = socios.Where( s => filter.Sc.Any(f => f == s.ScID));

Of course if you can compare object-to-object directly, the .Contains() is still adequate as long as you remember to use the return value.

like image 45
ryanyuyu Avatar answered Sep 19 '22 00:09

ryanyuyu