Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 me how to do it in LINQ?

Thanks.

like image 303
Bhaskar Avatar asked Nov 29 '22 16:11

Bhaskar


1 Answers

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

like image 55
Benjamin Podszun Avatar answered Dec 15 '22 06:12

Benjamin Podszun