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.
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));