Comparing two collections for equality irrespective of the order of items in them

后端 未结 19 1601
我在风中等你
我在风中等你 2020-11-22 10:28

I would like to compare two collections (in C#), but I\'m not sure of the best way to implement this efficiently.

I\'ve read the other thread about Enumerable.Sequen

19条回答
  •  孤街浪徒
    2020-11-22 11:18

    A duplicate post of sorts, but check out my solution for comparing collections. It's pretty simple:

    This will perform an equality comparison regardless of order:

    var list1 = new[] { "Bill", "Bob", "Sally" };
    var list2 = new[] { "Bob", "Bill", "Sally" };
    bool isequal = list1.Compare(list2).IsSame;
    

    This will check to see if items were added / removed:

    var list1 = new[] { "Billy", "Bob" };
    var list2 = new[] { "Bob", "Sally" };
    var diff = list1.Compare(list2);
    var onlyinlist1 = diff.Removed; //Billy
    var onlyinlist2 = diff.Added;   //Sally
    var inbothlists = diff.Equal;   //Bob
    

    This will see what items in the dictionary changed:

    var original = new Dictionary() { { 1, "a" }, { 2, "b" } };
    var changed = new Dictionary() { { 1, "aaa" }, { 2, "b" } };
    var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
    foreach (var item in diff.Different)
      Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
    //Will output: a changed to aaa
    

    Original post here.

提交回复
热议问题