如何比较两个无序序列(列表和数组)是否相等?
我有字符串数组,例如 string str[] = {"a", "b"}
和 List
如何确保字符串数组和列表包含相同的值。 注意:这些值可以是任意顺序,但必须具有相同的频率。
谁能告诉我如何在 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许我错过了一些东西,但为什么你不直接对
SequenceEqual()
进行比较保存 Jason 的字典方法(显然,应该也可以工作)并且对我来说似乎更自然/容易?
①:https://learn.microsoft.com/ en-us/dotnet/api/system.linq.enumerable.sequenceequal
Maybe I'm missing something, but why don't you just
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:
好的,由于顺序并不重要,但频率很重要,因此您需要对每个键进行计数,然后检查生成的键/计数对是否相等:
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:
您可以使用 Enumerable.SequenceEqual
You can use Enumerable.SequenceEqual