FindAll. Linq.

S

shapper

Hello,

I have two lists, A and B. Both are lists of an object named Obj which
has two properties: ID and Name.

I need to check if all items in A exist in B by comparing their names.

If yes, then return true. If not then return false.

Could someone, please, help me creating this?

I tried the following but it is not working:

bool FoundAll = (from b in B
join a in A on b.Name equals a.Name
select b).Any();

Thanks,
Miguel
 
P

Peter Morris

What about this?

bool result = list1.All(
i => ((from i2 in list2 where i2.ID == i.ID select i2).Count() > 0)
);
 
M

Martin Honnen

shapper said:
I have two lists, A and B. Both are lists of an object named Obj which
has two properties: ID and Name.

I need to check if all items in A exist in B by comparing their names.

If yes, then return true. If not then return false.

Could someone, please, help me creating this?

I tried the following but it is not working:

bool FoundAll = (from b in B
join a in A on b.Name equals a.Name
select b).Any();

I think you want
bool foundAll = A.All(t => B.Contains(t, new MyComparer()));
where you need to implement
class MyComparer : IEqualityComparer<Obj>
{
public bool Equals(Obj x, Obj y)
{
return x.Name == y.Name;
}

public int GetHashCode(Obj obj)
{
return obj.Name.GetHashCode();
}
}
 
S

shapper

I think you want
   bool foundAll = A.All(t => B.Contains(t, new MyComparer()));
where you need to implement
   class MyComparer : IEqualityComparer<Obj>
   {
         public bool Equals(Obj x, Obj y)
         {
             return x.Name == y.Name;
         }

         public int GetHashCode(Obj obj)
         {
             return obj.Name.GetHashCode();
         }
    }

You mean:

using System;
using System.Collections;

class MyComparer : IEqualityComparer<Object> {
public bool Equals(Object x, Object y) {
return x.Name == y.Name;
}

public int GetHashCode(Object obj) {
return obj.Name.GetHashCode();
}
}

I get the error:
The non-generic type 'System.Collections.IEqualityComparer' cannot be
used with type arguments

Any idea why?

Thanks,
Miguel
 
J

Jon Skeet [C# MVP]

You mean:

using System;
using System.Collections;

class MyComparer : IEqualityComparer<Object> {
public bool Equals(Object x, Object y) {
return x.Name == y.Name;
}

public int GetHashCode(Object obj) {
return obj.Name.GetHashCode();
}
}

I get the error:
The non-generic type 'System.Collections.IEqualityComparer' cannot be
used with type arguments

Any idea why?

Yes, you've used System.Collections instead of
System.Collections.Generic.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Linq. Where versus On 1
Linq. Aggregate 4
Linq Query 15
Equals() and inheritance 7
Compare Lists. How to? 7
Sub Query 2
Copy List 4
Problems overrideing the == operator 12

Top