3

I have two lists populated from different sources, what is the best way to check if both list contains the same items? Order is not important

List<Tuple<string, string, string>> list1;
List<Tuple<string, string, string>> list2;
Jimmy
  • 3,224
  • 5
  • 29
  • 47
  • so your check should return `true`, if they contain exactly the same items but possibly in different order? Or is it ok if one has more items? – Florian Koch Sep 21 '17 at 09:36
  • The "best" way is only something you can decide, not us. Have you tried to figure this out for yourself yet? What did you try? Show that code please, we're not going to write it for you. – DavidG Sep 21 '17 at 09:37
  • 1
    https://stackoverflow.com/questions/2060058/best-way-to-compare-two-large-string-lists-using-c-sharp-and-linq?rq=1 – René Vogt Sep 21 '17 at 09:37
  • @RenéVogt there is a difference between strings and tuples, though. But I agree that the general approach is the same, you just need to provide a comparer – Florian Koch Sep 21 '17 at 09:37
  • @FlorianKoch but not a difference that matters here, the default equality comparer for tuples uses the default equality comparer for all its elements. The question here is only how to compare lists, the type of the list elements doesn't really matter. – René Vogt Sep 21 '17 at 09:40

1 Answers1

12

You can use !Except.Any:

bool same = list1.Count == list2.Count && !list1.Except(list2).Any();

Explanation:

  1. check if both lists have the same Count, otherwise you know they don't contain the same
  2. then check with Except and Any if there are remeaining tuples if you "remove" list2 from list1. If there are Any(at least one) you know they don't contain the same

Works because tuples override GetHashCode(like anonymous types too) and string too.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939