通过另一个List / Array过滤Linq子集合 [英] Filter Linq Child Collection by another List/Array

查看:189
本文介绍了通过另一个List / Array过滤Linq子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试基于一个简单的值过滤一个小孩集合时,可以通过这样做来轻松实现:

When I try to filter a child collection based on a simple value I can do it easily by doing something like this:

db.Table.Where(a => a.SubTable.Any(b => b.SubTableId == 1));

但是,当我尝试根据对应的值列表过滤这个相同的子集合时,我'总是得到错误。

But when I try to filter this same child collection according a list of values that corresponds of it, I'm getting errors all the time.

List<long> listOfIDs = new List<long> { 1, 2, 3 };
db.Table.Where(a => listOfIDs.Any(a.SubTable.Select(b => b.SubTableId));

我搜索了很多如何做到这一点,我还在启动EF。我得到的错误是无法从System.Collections.Generic转换为Func。

I searched a lot how to do this and I'm still starting EF. The error I'm getting is Cannot convert from System.Collections.Generic to Func.

有人冷请帮我告诉我我做错了什么?我只想使用数组,列表,任何东西过滤一个集合...

Anybody cold please help me telling me what I'm doing wrong? I just want to filter a collection using an array, list, anything...

问候,
鲁本斯

Regards, Rubens

推荐答案

你几乎拥有了,你需要一种反转嵌套谓词中的逻辑来执行您正在搜索的集合,然后将lambda连续变量公开给我。我给出了一个更复杂的例子,说你有一个其他复杂对象的集合,并且你想要找到那些和他们的父母:

You almost had it. You need to kind of reverse the logic in the nested predicate to do the collection you are searching for and then expose the lambda continuation variable to that. I gave a little bit more complex example were say you have a collection of other complex objects and you want to find properties of those and their parents as well:

public class POC
{
  public int Id { get; set; }
  public string Desc { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Desc { get; set; }
}

static List<Order> GetOrders(int numberOfOrders)
{
  var orders = new List<Order>();

  for (int i = 1; i <= numberOfOrders; i++)
  {
    orders.Add(new Order { Id = i, Desc = $"{i} Order" });
  }

  return orders;
}

static List<POC> GetPOCOsAndOrders()
{
  return new List<POC>
  {
      new POC { Id = 1, Desc = "John", Orders = GetOrders(1)},
      new POC { Id = 2, Desc = "Jane", Orders = GetOrders(2) },
      new POC { Id = 3, Desc = "Joey" , Orders = GetOrders(3)}
  };
}


static void Main(string[] args)
{
  var orders = new List<int> { 2, 3 };
  var items = GetPOCOsAndOrders();

  var peopleAndOrdersWhereOrderNumberIsGreaterThanTwo = items.Where(x => x.Orders.Any(y => orders.Contains(y.Id)));

  //I should only get the last two people out of three and their orders
  peopleAndOrdersWhereOrderNumberIsGreaterThanTwo.ToList().ForEach(x => Console.WriteLine($"{x.Id} {x.Desc} {x.Orders.Count}"));

  Console.ReadLine();
}

这篇关于通过另一个List / Array过滤Linq子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆