Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compare list of tuples

Tags:

c#

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;
like image 488
Jimmy Avatar asked Nov 19 '25 07:11

Jimmy


1 Answers

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.

like image 117
Tim Schmelter Avatar answered Nov 20 '25 21:11

Tim Schmelter