I have a list of MyItem
objects called myItems
like this:
我有一个MyItem对象列表,叫做myItems:
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:
我想用选定类别的列表来过滤对象列表,这样过滤后的列表就会包含任何筛选类别id:
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:
如何在一行中使用LINQ呢?(如果可能的话,我也不能把我的头绕过去!)我的想象是:
IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Contains(xxx));
3 个解决方案
#1
2
var filtered = myItems.Where(x => x.category_ids.Intersect(filter)
.Any());
#2
2
Needs one more method call:
还需要一个方法调用:
IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Any(x=>filter.Contains(x));
#3
2
Another option than the one already presented:
除了已经提出的备选办法以外,还有一个办法:
var filtered = myItems.Where( item => item.category_ids.Intersect( filter ).Count() > 0 );
#1
2
var filtered = myItems.Where(x => x.category_ids.Intersect(filter)
.Any());
#2
2
Needs one more method call:
还需要一个方法调用:
IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Any(x=>filter.Contains(x));
#3
2
Another option than the one already presented:
除了已经提出的备选办法以外,还有一个办法:
var filtered = myItems.Where( item => item.category_ids.Intersect( filter ).Count() > 0 );