Check if one list contains any items from another

I'm just trying to return true if one list contains the name / value from list2:

This will be my structure:

public class TStockFilterAttributes { public String Name { get; set; } public String Value { get; set; } } List<TStockFilterAttributes> List1 = new List<TStockFilterAttributes>(); List<TStockFilterAttributes> List2 = new List<TStockFilterAttributes>(); 

This should return true:

 List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" }); List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" }); 

But this will return false, because Name && The value does not match:

 List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" }); List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Foo" }); 

Each list can contain many different values, and I just need to know if any of List1 matches any of List2.

I tried using:

 return List1.Intersect(List2).Any(); 

but this seems to return false in all cases, I assume it is because I keep the class in List, and not a simple int / string?

+8
c # linq
source share
5 answers

Override Equals and GetHashCode implementation for your class:

 public class TStockFilterAttributes { public String Name { get; set; } public String Value { get; set; } public override bool Equals(object obj) { TStockFilterAttributes other = obj as TStockFilterAttributes; if (obj == null) return false; return Name == obj.Name && Value == obj.Value; } public override int GetHashCode() { return Name.GetHashCode() ^ Value.GetHashCode(); } } 

Or provide a comparison with the Intersect function.

+7
source share

Assuming performance doesn't matter:

 List1.Any(l1 => List2.Any(l2 => l1.Key == l2.Key && l1.Value == l2.Value)); 

Alternatives would be to override Equals or make it Struct (possibly not appropriate)

+5
source share
 var query = List1.Where(x => List2.Exists(y => y.Name == x.Name && y.Value == x.Value)); 

But performance can be poor

+3
source share

The problem is that you are comparing links, not objects. Since each time you create a new object, lists will never contain the same links.

Try:

 var FooBar = new TStockFilterAttributes { Name = "Foo", Value = "Bar" }; var FooFoo = new TStockFilterAttributes { Name = "Foo", Value = "Foo" }; List1.Add(FooBar); List2.Add(FooBar); List2.Add(FooFoo); return List1.Intersect(List2); 
+1
source share

late to run into, but with intersection we can use select and avoid using equality.

 list1.Select(Function(p) p.ItemID).Intersect(list2.Select(Function(p)p.ItemID)).Any() 
0
source share

All Articles