聚合具有相同键的对象中的列表

Aggregating lists within objects having the same key

如果我有一个包含以下参数的 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() 的运气,但到目前为止没有运气。

您可以按键对它们进行分组,并使用 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();