比较 LINQ where 子句中的两个对象列表

Compare two list of objects in where clause of LINQ

我想使用 LINQ 根据属性比较两个对象列表。我创建了一个对象列表,另一个列表存储在数据库中。 类如下:

class A
{
    int a1;
    int a2;
} 
class B
{
    int b1;
    int b2;
}

我正在使用条件 (a1==b1 and a2==b2)(a1==b2 and a2==b1) 比较 List<A> aList<B> b。如果任何条件成立,它 returns 第三个 List<C> 具有 class A 的属性。 这是我正在使用的以下 LINQ:

(from a in context.A
                 where b.Any(m => (m.b1 == a.a1 && m.b2 == a.a2) || (m.b1 == a.a2 && m.b2 == a.a1))
                 select new C
                 {
                     c1 = a.a1,
                     c2 = a.a2,
                 }).ToList();

但是它抛出一个错误:

Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator

请帮我找出正确的 Linq 查询。

这样试试

context.A.Where(a=>b.Any(m => (m.b1 == a.a1 && m.b2 == a.a2) || (m.b1 == a.a2 && m.b2 == a.a1))).select(a=> new C{ c1 = a.a1,
                     c2 = a.a2});

试试这个:

(
    from a in context.A.ToArray()
    where b.Any(m => (m.b1 == a.a1 && m.b2 == a.a2) || (m.b1 == a.a2 && m.b2 == a.a1))
    select new C
    {
        c1 = a.a1,
        c2 = a.a2,
    }
).ToList();

这带来了 A 本地,然后允许您使用也​​是本地的 b

当然,这只有在 A 小到足以首先完全加载到内存中时才有效。