Thursday, March 24, 2016

Finding matching values between 2 collections using LINQ

If you ever have a requirement to find matching values between 2 collections (especially if they are collections of classes) using LINQ, you might be wondering exactly how to accomplish this.

Well, fortunately, there are multiple solutions on solving this dilemma!

The most readily obvious solution involves leveraging properties on these classes which consist of primitive types such as strings as follows:


public class MyClass
{
    public string Name {get; set;}
}

List<MyClass> coll1 = new List<MyClass>()
{
  new MyClass() {Name="Value1"},
  new MyClass() {Name="Value2"}
 };

List<MyClass> coll2 = new List<MyClass>()
{
  new MyClass() {Name="Value1"},
  new MyClass() {Name="Value3"},
  new MyClass() {Name="Value2"}
 };

 
var results = coll2.Where(x => coll1.Any(z => z.Name == x.Name));

Therefore, by using the Any extension, you can find matching values.

Alternatively, you can also override the Equals method in your class so that you can use the .Contains method as follows:


public class MyClass
{
 public string Name {get; set;}

 public override bool Equals(Object obj)
 {
  if (obj == null || GetType() != obj.GetType()) 
  {
   return false;
  }
  
  MyClass t = (MyClass)obj;

    if (t.Name.Equals(this.Name))
    {
  return true;
  }//if
  
  return false;
 }

 public override int GetHashCode()
 {
  return base.GetHashCode();
 }

}

var results = coll2.Where(x => coll1.Contains(x)).ToList();

That is all you need to do!!

No comments:

Post a Comment