Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Aggregating lists within objects having the same key

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading