Home > Back-end >  Aggregating lists within objects having the same key
Aggregating lists within objects having the same key

Time:01-21

If I have a list of Issue objects that have the following parameters: List<int> ids, string key that looks like this:

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

I am looking for a way to aggregate these two Issue objects by their key such that there would only be 1 item like this in the list, but with two ids in the list of ints. Something which can be translated to:

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

Currently, my idea would be to just parse through the list and do different validations, but I was wondering whether there's a "quick" way of doing this. Tried my luck with Aggregate() but with no luck so far.

CodePudding user response:

you could group them by the key and for each key flatten the ids list using SelectMany:

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