Search code examples
c#linqiequalitycomparer

See items that match in two list


lest say I have two lists

List1:

"Tom", "Frank", "Lacey"

List2:

"Frank", "Tom"

what would be the query needed to show that Tom and Fran are being repeated?

The lists that I am trying to compare are very big and if I do something like:

 var q = from a in List1
         from b in List2
         where a.Name == b.Name
         select a;

this takes a long time.


Solution

  • To see what values are duplicated across lists, you can use

    var results = list1.Intersect(list2);
    

    If you were otherwise interested in matching the items and doing something with each, you could use Join

    var results = from item1 in list1 
                  join item2 in list2 
                  on item1 equals item2 
                  select new 
                  {
                      // include what you want here
                  };
    

    In your case, since you are dealing with a list of strings, Intersect seems like the appropriate course of action. If you were dealing with matching lists of objects on a common key, you might opt to join the lists and project the results.