当我尝试根据一个简单的值过滤子集合时,我可以通过这样的方式轻松完成:
db.Table.Where(a => a.SubTable.Any(b => b.SubTableId == 1));
但是当我尝试根据与其对应的值列表过滤同一个子集合时,我一直都会遇到错误。
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。
任何人请帮我告诉我我做错了什么?我只是想使用数组,列表,任何东西来过滤集合......
此致 鲁
答案 0 :(得分:4)
您可以尝试如下所示。
db.Table.Where(a => a.SubTable.Any(x=> listOfIDs.Contains(x.SubTableId)));
答案 1 :(得分:1)
你几乎拥有它。您需要反转嵌套谓词中的逻辑来执行您要搜索的集合,然后将lambda continuation变量公开给它。我给了一些更复杂的例子说你有其他复杂对象的集合,你想找到那些及其父母的属性:
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();
}
答案 2 :(得分:0)
试试这个:
var ResultList=(
from elemID in listOfIDs
from elemA in db.Table.Where(elemA => elemA.SubTable.Contains(elemID)).DefaultIfEmpty()
where elemA !=null
select elemA).ToList();
答案 3 :(得分:0)
尝试从SubTable开始:
apply()
或者如果您愿意
var results = from s in SubTable
join id in listOfIDs on s.SubTableID equals id.ID
select s.Table;
最后,如果您无权访问SubTable表
var results = subTables.Where(a => listOfIDs.Contains(a.SubTableID))
.Select(s => s.Table);