How can I compare two unordered sequences (list and array) for equality?
I have string array say string str[] = {"a", "b"}
and List<string> lst = new List<string> {"a", "b"}
How can I make sure that both string array and list contains the same values. Note: The values can be in any order but must have the same frequency.
Can anyone tell m开发者_运维问答e how to do it in LINQ?
Thanks.
Maybe I'm missing something, but why don't you just
- Sort both (since order is irrelevant for you)
- Compare the results with
SequenceEqual()
¹
Saves the dictionary approach of Jason (which, obviously, should work as well) and seems more natural/easy to me?
①: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal
The accepted answer seems somewhat awkward to me. Why can't you just do:
bool equals = str.OrderBy(s => s).SequenceEquals(lst.OrderBy(t => t));
Okay, since order does not matter but frequncies do, you need to count each key, and then check that the resulting pairs of keys/counts 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));
You can use Enumerable.SequenceEqual
string[] str =new [] {"a", "b"};
List<string> lst = new List<string> {"a", "b"};
bool result=str.SequenceEqual(lst);
精彩评论