我想比较两个对象的所有可能的变化。我怎样才能做到这一点。
var _entries = new List<string>();
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
int count = 0;
for (int i = 1; i < _entries.Count; i++)
{
if (_entries[i].Equals(_entries[i - 1]))
{
count++;
}
}
Console.Write(count);
Console.ReadLine();
此比较按顺序进行比较,但它应该与每种可能场景进行比较。
预期结果应该是 4
,因为数组中有 4
个相同的对象。
最佳答案
我建议使用Linq,GroupBy :
using System.Linq;
...
// No Sequential Order test
var _entries = new List<string>() {
"Awesom",
"Bar",
"Awesom",
"Awesom",
"Foo",
"Awesom",
"Bar",
};
int count = _entries
.GroupBy(item => item)
.Sum(group => group.Count() - 1);
在GroupBy
的帮助下,我们获得了3
组:
4 items of "Awesom"
1 items of "Foo"
2 items of "Bar"
然后我们可以对每组中的项目进行计数
并对它们进行求和
:(4 - 1) + (1 - 1) + (2 - 1) == 4
总体重复。
关于c# - 如何将所有对象相互比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56854272/