LINQ group lists

本文关键字:lists group LINQ | 更新日期: 2023-09-27 18:27:03

在LINQ中,是否可以对int的唯一序列进行分组?假设我有一个类,每个类都有一个List属性。每个对象(称为foo)都有一个int列表{1}、{1,2,4}、{4,5,6}、{1}和{1,2,4}。我该如何使用一个组,这样我就可以得到这些组:

List<foo> foos// has 5 elements
/*
groups:
1. 2 {1}
2. 2 {1. }
3. {4, 5, 6}
*/

LINQ group lists

您必须使用GroupBy重载,该重载接收键的IEqualityComparer。

var groups = foos.GroupBy(thefoo => thefoo.IntListProp, new IntListComparer());

其中IntListComparerIEqualityComparer的自定义实现,可能类似于:

class IntListComparer : IEqualityComparer<List<int>> {
    public bool Equals(List<int> x, List<int> y) {
        if (x == y)
            return true;
        if (x == null || y == null)
            return false;
        if (x.Length != y.Length)
            return false;
        using (var xenum = x.GetEnumerator()) {
            foreach (int yval in y) {
                xenum.MoveNext();
                if (yval != xenum.Current)
                    return false;
            }
        }
        return true;
    }
    // You also have to implement the GetHashCode which
    // must have the property that
    // if Equals(x, y) => GetHashCode(x) == GetHashCode(y)
    public int GetHashCode(List<int> x) {
        int hashcode = 1;
        const int primeMultiplier = 17;
        foreach (int xval in x)
            hashchode *= primeMultiplier * xval;
        return hashcode;
    }
}