c# - 如何将所有对象相互比较?

标签 c# .net

我想比较两个对象的所有可能的变化。我怎样才能做到这一点。

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 个相同的对象。

最佳答案

我建议使用LinqGroupBy :

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/

相关文章:

c# - MongoDB C# 驱动程序 IAsyncCursor<BsonDocument> 行为?

C# Office Development : Microsoft. Office.Tools.Word.Controls.Button 给出错误

c# - 如何使用 C# Windows 窗体创建流畅的动画?

.net - 为什么 ActualSize 没有在 WPF 上更新其值?

c# - 如何将两种方法转换为一种方法以提高效率?

c# - 使用表达式树生成排序列表

c# - 序列不包含匹配元素 - EntityFramework

c# - Windows Phone 7 开发中 UITableView 的等价物是什么?

c# - ViewModel 中对象的验证不添加 CSS 验证类

.net - 在 Windows 7 中使用 .NET Windows 服务显示消息框