【问题标题】:C# merge multiple lists by id and summing the propertyC#通过id合并多个列表并对属性求和
【发布时间】:2017-04-29 10:16:57
【问题描述】:

我有一个如下所示的图形类:

public class Graphic
{
    public int id { get; set; }
    public int Counter { get; set; }
}

现在我有 3 个 grapic 列表:

public void myFunction()
{
    List<Graphic> l1= new List<Graphic> ();
    List<Graphic> l2= new List<Graphic> ();
    List<Graphic> l3= new List<Graphic> ();

    l1.Add(new Graphic {id = 1, Counter = 4});
    l1.Add(new Graphic {id = 2, Counter = 2});
    l1.Add(new Graphic {id = 3, Counter = 9});
    l1.Add(new Graphic {id = 4, Counter = 1});

    l2.Add(new Graphic {id = 1, Counter = 1});
    l2.Add(new Graphic {id = 2, Counter = 2});
    l2.Add(new Graphic {id = 3, Counter = 3});
    l2.Add(new Graphic {id = 5, Counter = 1});

    l3.Add(new Graphic {id = 1, Counter = 12});
    l3.Add(new Graphic {id = 7, Counter = 1});
    l3.Add(new Graphic {id = 8, Counter = 3});
    l3.Add(new Graphic {id = 4, Counter = 1});
}

我需要一个代码来合并这 3 个列表,每个图形及其 ID 和计数器属性将被汇总,因此结果将是:

var mergedList = {
    Graphic {id = 1, Counter = 17},
    Graphic {id = 2, Counter = 4},
    Graphic {id = 3, Counter = 12},
    Graphic {id = 4, Counter = 2},
    Graphic {id = 5, Counter = 1},
    Graphic {id = 7, Counter = 1},
    Graphic {id = 8, Counter = 3}
}

任何想法都会帮助我。 有没有办法使用 LINQ 有效地做到这一点?

【问题讨论】:

  • 是的。看过 groupby 吗?

标签: c# .net list linq


【解决方案1】:

使用.Concat合并3个列表,然后GroupBy得到不同ids的所有Counter值:

var result = l1.Concat(l2)
               .Concat(l3)
               .GroupBy(item => new { item.id, item.Geometry }, item => item.Counter)
               .Select(group => new Graphic
               {
                   id = group.Key,
                   Counter = group.Sum()
               }).ToList();

请参阅集合初始化器以更简洁地初始化列表:

List<Graphic> l1 = new List<Graphic>
{
    new Graphic { id = 2, Counter = 2 },
    new Graphic { id = 3, Counter = 9 },
    new Graphic { id = 4, Counter = 1 },
    new Graphic { id = 1, Counter = 4 },
};

我还建议阅读 C# naming conventions 以了解函数和属性的命名。

【讨论】:

  • 谢谢!这适用于这个例子。但是,如果我有另一个 Graphic 的属性,名为 'geometry' ,我想包含在合并的图形中,但不总结它,只需将他复制到合并的图形中。我可以在 LINQ 中这样做吗?
  • @RonAvraham - 是的,但你需要看看你想要的行为是什么?您对每个 id 都有唯一的价值吗?如果是这样,则将其添加到 group by,如果不是,那么您需要定义您想要的行为(例如串联、first、last....)
  • 每个 id 在所有 3 个列表中都具有相同的“几何”。我只想将其中一个带到合并的图形中。
  • @RonAvraham - 然后将其添加为 GroupBy 密钥的一部分。查看更新
  • @RonAvraham - 欢迎您。下次尝试查看不同的文档和 SO linq 文档;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多