如何比较两个无序序列(列表和数组)的相等性? [英] How can I compare two unordered sequences (list and array) for equality?
本文介绍了如何比较两个无序序列(列表和数组)的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数组,说string str[] = {"a", "b"}
I have string array say string str[] = {"a", "b"}
和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.
有人可以告诉我如何在LINQ中做到这一点吗?
Can anyone tell me how to do it in LINQ?
谢谢.
推荐答案
好吧,由于顺序无关紧要,但频率却如此,因此您需要对每个键进行计数,然后检查生成的键/计数对是否相等:
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));
这篇关于如何比较两个无序序列(列表和数组)的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文