【问题标题】:Aggregating lists within objects having the same key在具有相同键的对象中聚合列表
【发布时间】:2022-01-21 11:11:14
【问题描述】:

如果我有一个具有以下参数的 Issue 对象列表:List<int> idsstring key,看起来像这样:

List<Issue> issues = new List<Issue>()
{
   new Issue()
   {
      ids = new List<int>(){1},
      key = "CODE1"
   },
           
   new Issue()
   {
      ids = new List<int>(){2},
      key = "CODE1"
   }
};

我正在寻找一种方法来通过它们的key 聚合这两个Issue 对象,这样列表中只有一个这样的项目,但整数列表中有两个ids。可以翻译成的东西:

List<Issue> issues = new List<Issue>()
{
   new Issue()
   {
      ids = new List<int>(){1, 2},
      key = "CODE1"
   }
};

目前,我的想法是只解析列表并进行不同的验证,但我想知道是否有一种“快速”的方式来做到这一点。用Aggregate() 试试运气,但到目前为止没有运气。

【问题讨论】:

  • 请使用Aggregate发布您的尝试

标签: c# list linq


【解决方案1】:

您可以按键对它们进行分组,并为每个键使用 SelectMany 展平 ids 列表:

List<Issue> agregated = issues.GroupBy(x => x.key)
    .Select(g => new Issue
        {
            key = g.Key, 
            ids = g.SelectMany(s => s.ids).ToList()
        }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2015-04-10
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多