LINQ组列表

时间:2015-12-17 01:57:59

标签: c# linq

在LINQ中,是否可以对一个唯一的整数序列进行分组?假设我有一个类,每个类都有一个List属性。每个对象(比如它的名为foo)都有一个这样的整数列表{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}

*/

1 个答案:

答案 0 :(得分:2)

您必须使用接收IEqualityComparer的GroupBy重载作为密钥。

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;
    }
}