Vivek
Vivek

Reputation: 373

Compare two list of objects in where clause of LINQ

I want to compare two list of objects on the basis of their properties using LINQ. I have created a list of objects and another list is stored in database. The classes are as following:

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

I am comparing List<A> a to List<B> b using conditions (a1==b1 and a2==b2)or (a1==b2 and a2==b1). if any condition gets true it returns a third List<C> with properties of class A. Here is the following LINQ I am using:

(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();

But its throwing an error as:

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

please help me to figure out right Linq query.

Upvotes: 1

Views: 3319

Answers (2)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

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});

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117057

Try this:

(
    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();

This brings A local which then allows you to use b which is also local.

Of course, this only works if A is small enough to be fully loaded in memory first.

Upvotes: 2

Related Questions