我有一个List<Array>
,我正在使用 LINQ 来查找重复项并进行计数,但它不起作用。
看图你可以看到,lstMyList[0]和lstMyList[11]在Int[]中具有相同的值
这是 lstMyList 定义:
List<Array> lstMyList = new List<Array>();
我使用了代码,但它不起作用:
var group = lstMyList.GroupBy(t => t).ToArray();
或
Dictionary<int[], int> count = lstMyList.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
这是图片:http://imageshack.com/a/img69/2552/h114.png
也许有人可以给我关于我的问题的提示。
最佳答案
首先创建比较器类:
sealed class ArrayEqualityComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
if (x == null && y == null)
return true;
if (x != null && y != null)
return x.SequenceEqual(y);
return false;
}
public int GetHashCode(int[] obj)
{
return obj.Length;
}
}
然后您可以在 GroupBy 子句中使用它。
List<int[]> lstMyList = new List<int[]> { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 1, 2 } };
var groups = lstMyList.GroupBy(t => t, new ArrayEqualityComparer())
.Select(g => new { g.Key, Count = g.Count() })
.ToArray();
关于c# - 如何在 LINQ 中对列表数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22753976/