0

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.

Tono Nam
  • 34,064
  • 78
  • 298
  • 470

3 Answers3

4

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.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
3

You should use Intersect:

var items = List1.Intersect(List2); // Tom, Frank
alexn
  • 57,867
  • 14
  • 111
  • 145
3

You can use intersect:

List<string> list3 = list1.Intersect(list2).ToList();
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283