Reputation: 22964
I have a list of MyItem
objects called myItems
like this:
public class MyItem{
public int[] category_ids;
public string name;
}
List<MyItem> myItems;
I want to filter down the list of objects with a list of selected categories so that the filtered list contains ANY of the filter category ids:
int[] filter = { 1, 5, 6, 9 };
How would I do that using LINQ in one line? (if its even possible, I cant wrap my head around it!) I imagine something along the lines of:
IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Contains(xxx));
Upvotes: 2
Views: 117
Reputation: 75306
var filtered = myItems.Where(x => x.category_ids.Intersect(filter)
.Any());
Upvotes: 2
Reputation: 48230
Another option than the one already presented:
var filtered = myItems.Where( item => item.category_ids.Intersect( filter ).Count() > 0 );
Upvotes: 2
Reputation: 12849
Needs one more method call:
IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Any(x=>filter.Contains(x));
Upvotes: 2