0

There are 2 large list of objects, where I need to do a where clause and find the matching records.

List<A> a= ...;
List<A> b = ...;

A model

Id

Name

Age

Address

I need to return a list that contains all the object of List after comparing with List.

The properties I should check is : If the Ids are equal, if the Names are equal and if the ages are equal.

List<A> common = a.Where(n => b.Select(o => o.Id).Contains(n.Id))
     .Where(n => b.Select(o => o.Name).Contains(n.Name))
     .Where(n => b.Select(o => o.Age).Contains(n.Age))

There should be something wrong with this, as it returns a Null.

Community
  • 1
  • 1
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • 1
    If you want only the matching items after the comparison, you should use `Intersect` LINQ method. You also want to compare only few properties of objects so you should write and implementation of IComparer interface and use it in Intersect method. https://stackoverflow.com/questions/4340273/intersect-with-a-custom-iequalitycomparer-using-linq – Chetan Apr 25 '19 at 01:44
  • Didn't you try with join?? – Udara Kasun Apr 25 '19 at 01:44
  • @UdaraKasun Can join work when I have multiple conditions ? Newbie. – Sharon Watinsan Apr 25 '19 at 01:50

1 Answers1

1

You can create custom EqualityComparer:

public class ModelEqualityComparer : IEqualityComparer<Model>
{
    public bool Equals(Model x, Model y)
    {
        return x.Id == y.Id && x.Name == y.Name && x.Age == y.Age;
    }

    ...
}

And use it like this:

var intersect = a.Intersect(b, new ModelEqualityComparer());

If you want just LINQ solution:

List<Model> common = a
   .Where(q => b.Any(w => w.Id == q.Id && w.Name == q.Name && q.Age == w.Age))
koryakinp
  • 3,989
  • 6
  • 26
  • 56
  • Is there a way to do it without a Customer class ? – Sharon Watinsan Apr 25 '19 at 02:22
  • So when you use Any, will it compare `a` with `b` and give me what is common in `a`only ? Hope I made it clear ;) . Also, I have around 800K+ records, I tried your approach and it takes a lot of time. Like 5 minutes. so can we optimize this code? – Sharon Watinsan Apr 25 '19 at 02:35