如何使用LINQ对列表列表进行分组(例如:List< List< int>>)) [英] How to group a list of lists using LINQ (ex: List<List<int>>)

查看:476
本文介绍了如何使用LINQ对列表列表进行分组(例如:List< List< int>>))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用一些for循环轻松地做到这一点,但是我想看看是否有一种方法可以使用流畅的LINQ.我正在尝试找出每个子列表中有多少个.

I know I can easily do this with some for loops, but wanted to see if there was a way to do it with fluent LINQ. I'm trying to find out how many of each sub-list I have.

我正在查看 ,但无法与GroupBy()

I was looking at Enumerable.SequenceEqual but couldn't get it working with GroupBy()

说我有一个像这样的List<List<int>:

{
 {1,2}
 {2, 3, 4}
 {1,2}
 {1,3}
 {1,2}
}

我想按相等的列表将其分组,就像这样

and I want to group it by equal lists, like so

{
 <3, {1,2}>
 <1, {2, 3, 4>
 <1, {1,3}
}

推荐答案

您需要实现IEqualityComparer<List<T>>,然后可以将其传递给GroupBy.例如:

You'd need to implement a IEqualityComparer<List<T>>, which you can then pass into GroupBy. For example:

public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
    public bool Equals(List<T> lhs, List<T> rhs)
    {
        return lhs.SequenceEqual(rhs);
    }

    public int GetHashCode(List<T> list)
    {
        unchecked
        {
            int hash = 23;
            foreach (T item in list)
            {
                hash = (hash * 31) + (item == null ? 0 : item.GetHashCode());
            }
            return hash;
        }
    }
}

然后:

var counts = lists.GroupBy(x => x, 
                           (key, lists) => new { List = key, Count = lists.Count() },
                           new ListEqualityComparer<int>());

这篇关于如何使用LINQ对列表列表进行分组(例如:List&lt; List&lt; int&gt;&gt;))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆