【问题标题】:How to group list of lists by sublist如何按子列表对列表列表进行分组
【发布时间】:2021-07-11 04:43:57
【问题描述】:

输入:两个整数列表的列表

List<List<int>> lists = new List<List<int>>() {
  {1,2},
  {20,21},
  {3,2},
  {21,55}
};

输出:具有相同第一个OR第二个整数值的两个整数列表

{
  {{1,2}, {3,2}}, 
  {{20,21}, {21,55}}
}

【问题讨论】:

  • How to Askminimal reproducible example 会很好。 “两个整数列表的列表”?那两个整数是元组吗?和数组?密钥对?具有 2 个属性的对象?你有最小样本的初始化吗?和预期的结果。是否要在嵌套嵌套的地方进行分组。还是扁平的?
  • 请提供 input 和预期 resultexample
  • 好的,如果内部元素是一个列表,你确定 group by 总是有 2 个元素吗?可以有更多吗?可能会少一点吗?或者你需要提防那个
  • 请问{{1, 2}, {3, 2}, {2, 5}} 的预期答案是什么?
  • 同样的 {{1, 2}, {3, 2}, {2, 5}}

标签: c# linq


【解决方案1】:

https://dotnetfiddle.net/Udb15ewriting a custom comparer for linq groupby 中所述,在编写自己的IEqualityComparer 时,必须实现EqualsGetHashCode
但是GetHashCode 将首先被调用,如果它们不同,Equals 将不会被调用。
所以我们需要强制GetHashCode 为常量。

// https://stackoverflow.com/questions/5231845/c-sharp-linq-group-by-on-multiple-columns
class ListFirstTwoComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> a, List<int> b)
    {
        var a2 = a.Take(2);
        var b2 = b.Take(2);

        //https://stackoverflow.com/questions/11092930/check-if-listt-contains-any-of-another-list
        return  a2.Any(x => b2.Any(y => y == x));
    }

    public int GetHashCode(List<int> input)
    {
        return 0;       
    }
}

var result = lists.GroupBy(p => p, new ListFirstTwoComparer());

结果:

[
    {    
        {1,2},
        {1,2},
        {3,2}        
    },
    {        
        {20,21},
        {21,22}        
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多