【问题标题】:Using LINQ how can I check for an instance of a number in one array, in another array?使用 LINQ 如何检查一个数组和另一个数组中的数字实例?
【发布时间】:2012-09-25 11:11:15
【问题描述】:

我有一个名为 myItemsMyItem 对象列表,如下所示:

public class MyItem{
    public int[] category_ids;
    public string name;
}

List<MyItem> myItems;

我想用选定类别列表过滤对象列表,以便过滤后的列表包含任何过滤器类别 ID:

int[] filter = { 1, 5, 6, 9 };

如何在一行中使用 LINQ? (如果可能的话,我不能绕着它转!) 我想像这样的事情:

IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Contains(xxx));

【问题讨论】:

    标签: c# arrays linq contains


    【解决方案1】:
    var filtered = myItems.Where(x => x.category_ids.Intersect(filter)
                                              .Any());
    

    【讨论】:

      【解决方案2】:

      除了已经提出的选项之外的另一个选项:

      var filtered = myItems.Where( item => item.category_ids.Intersect( filter ).Count() > 0 );
      

      【讨论】:

        【解决方案3】:

        还需要一个方法调用:

        IEnumerable<MyItem> filtered = myItems.Where(item => item.category_ids.Any(x=>filter.Contains(x));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-30
          • 1970-01-01
          • 1970-01-01
          • 2013-03-16
          • 2023-03-24
          相关资源
          最近更新 更多