C # Merge List of auxiliary objects from parent level List of objects

If you have a list and want to combine a sub-list for any SomeObject that has the same Id field, how do you do it? Here is an example of objects:

public class SomeObject { public string Name { get; set; } public int Id { get; set; } public List<KeyPair> ValuePairs {get;set;} } public class KeyPair { public string Key { get; set; } public string Value { get; set; } } 

And this is an example of creating a list of layouts:

 List<SomeObject> objects = new List<SomeObject>(); objects = new List<SomeObject>() { new SomeObject { Name="Rando Object 1", Id=5, ValuePairs=new List<KeyPair>() { new KeyPair { Key="TestKey1", Value="TestValue1" }, new KeyPair { Key="TestKey2", Value="TestValue2" } } }, new SomeObject { Name="Rando Object 2", Id=5, ValuePairs=new List<KeyPair>() { new KeyPair { Key="TestKey3", Value="TestValue3" }, new KeyPair { Key="TestKey4", Value="TestValue4" } } } }; 

What type of Linq or related query do you need to make in order to create a new SomeObject list that is combined based on any top level SomeObject that has corresponding Id fields; then combine the KeyPair list into one list. So you will have SomeObject Id = 5, and then four key pair values ​​combined from two different previous SomeObjects in the list. The name value can be excluded from the new object.

Any ideas? Thank you very much.

+5
source share
3 answers

You need to group them using Id and use SelectMany to select the KeyPair list.

 var result = objects.GroupBy(o => o.Id).Select(group => new SomeObject { Id = group.Key, ValuePairs = group.SelectMany(x => x.ValuePairs).ToList() }).ToList(); 
+4
source

You can try the following:

 var res = objects.GroupBy(o => o.Id) .Select(group => new { Id = group.Key, ValuePairs = group.SelectMany(g => g.ValuePairs) }); 

Original post:

 var res = objects.Where(o => o.Id == 5).SelectMany(o => o.ValuePairs); 
+2
source

Use this function

https://dotnetfiddle.net/aE6p5H

 public List<SomeObject> MergeObj(List<SomeObject> someObjects) { var idList = someObjects.Select(x => x.Id).Distinct().ToList(); var newSomeObjects = new List<SomeObject>(); idList.ForEach(x => { var newValuePairList = new List<KeyPair>(); someObjects.Where(y => y.Id == x).ToList().ForEach(y => { newValuePairList.AddRange(y.ValuePairs); }); newSomeObjects.Add(new SomeObject{Id = x, ValuePairs = newValuePairList}); }); return newSomeObjects; } 
0
source

Source: https://habr.com/ru/post/1267214/


All Articles