If you had a List and wanted to merge the sub List for any SomeObject's that have the same Id field how would you do that? Here are the example 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 the sample creation of a mock list:
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 sort of Linq or related query would you need to do to create a new list of SomeObject that is merged based on any top level SomeObject's that have matching Id fields; to then combine their KeyPair list to a single list. So you would have SomeObject Id=5 and then 4 key pair values merged from the two different previous SomeObject's in the list. The name value could be left out from the new object.
Any ideas? Thank you so much.
You need to group them by Id
and use SelectMany
to select KeyPair
list.
var result = objects.GroupBy(o => o.Id).Select(group => new SomeObject
{
Id = group.Key,
ValuePairs = group.SelectMany(x => x.ValuePairs).ToList()
}).ToList();
You can try this:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With