The scenario I have is as follows:
I have the following data -
1, samename, Rock, New York, 12
2, samename, Jazz, Sydney, 12
3, samename, Rock, Sydney, 12
4, samename, Jazz, New York, 12
5, name3, Opera House, Sydney, 14
6, name3, Opera House, London, 14
7, name2, Emirates, London, 13
And I would like to output it flattened based on the GroupID like below
1, samename, {Rock,Jazz}, {New York,Sydney}, 12
5, name3, Opera House, {Sydney,London}, 14
7, name2, Emirates, London, 13
This was really bad design that I have inherited - and I am trying to make it better.. without breaking the old code.
I believe the answer is something to do with SelectMany - but I can't work out the syntax - I've tried a few different ways.
my attempted solution - without flattening..
var q3 = Data.Where(b=>b.GroupID != null).GroupBy(x=> new { x.GroupID }, (key, group) => new
{
GroupID = key.GroupID,
Result = group.Select(g=> new
{
Type = g.Type,
Location = g.Location,
}).ToList()
});
Try this:
var answer = data.GroupBy(x => x.GroupID).Select(x => new {
ID = x.Min(y => y.ID),
Name = x.Select(y => y.Name).ToList(),
Type = x.Select(y => y.Type).ToList(),
Location = x.Select(y => y.Location).ToList(),
GroupID = x.Key
}).ToList();
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