lst...">

How can I compare two unordered sequences (list and array) for equality?

I have a string array string str[] = {"a", "b"}

and List<string> lst = new List<string> {"a", "b"}

How can I make sure that both the string array and the list contain the same values. Note. The values ​​can be in any order, but must have the same frequency.

Can someone tell me how to do this in LINQ?

Thank.

+3
source share
4 answers

Well, since the order doesn’t matter, but frequncies do, you need to count each key and then check that the resulting key / counter pairs are equal:

var first = str.GroupBy(s => s)
               .ToDictionary(g => g.Key, g => g.Count());

var second = lst.GroupBy(s => s)
                .ToDictionary(g => g.Key, g => g.Count());

bool equals = first.OrderBy(kvp => kvp.Key)
                   .SequenceEquals(second.OrderBy(kvp => kvp.Key));
+1
source

Maybe I missed something, but why don't you just

  • Sorting both (since the order is irrelevant for you)
  • Compare results with SequenceEquals()

(, , ) /?

+10

. :

bool equals = str.OrderBy(s => s).SequenceEquals(lst.OrderBy(t => t));
+4

You can use Enumerable.SequenceEqual

  string[] str =new [] {"a", "b"};
  List<string> lst = new List<string> {"a", "b"};
  bool result=str.SequenceEqual(lst);
-1
source

All Articles