按数组内容分组 [英] Group by array contents
问题描述
我有一个List<Tuple<string,long,byte[]>>
,我想按字节数组的内容分组.
I have a List<Tuple<string,long,byte[]>>
and I want to group by the contents of the byte array.
有没有一种简单的方法可以使用GroupBy
和lambda来做到这一点?
Is there a simple way to do this with GroupBy
and a lambda?
理想情况下,我希望不创建中间数据结构(例如用于保存数组元素的字符串)来做到这一点.
Ideally, I want to do this without creating an intermediate data structure (like a string to hold the elements of the array).
推荐答案
您可以使用自定义IEqualityComparer<byte[]>
(甚至更好的是通用的IEqualityComparer<T[]>
)实现来实现:
You can achieve that using custom IEqualityComparer<byte[]>
(or even better, generic one: IEqualityComparer<T[]>
) implementation:
class ArrayComparer<T> : IEqualityComparer<T[]>
{
public bool Equals(T[] x, T[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(T[] obj)
{
return obj.Aggregate(string.Empty, (s, i) => s + i.GetHashCode(), s => s.GetHashCode());
}
}
我很确定GetHashCode
可以实现得更好,但这只是一个例子!
I'm pretty sure GetHashCode
could be implemented much better, but it's just an example!
用法:
var grouped = source.GroupBy(i => i.Item3, new ArrayComparer<byte>())
这篇关于按数组内容分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!