Maske
Maske

Reputation: 864

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?

Upvotes: 6

Views: 15085

Answers (2)

D Stanley
D Stanley

Reputation: 152521

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.

Upvotes: 12

ryanyuyu
ryanyuyu

Reputation: 6486

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.

Upvotes: 1

Related Questions