given this Records
class Record
{
DateTime Date {get; set;}
string Article {get; set;}
string Platform { get; set;}
string Amount { get; set;}
}
With a sql query I get a list of Records and want to Group the Platforms by Article.
I do this query:
List<Record> recordList = FetchRecords();
var group = recordList.GroupBy(
f => f.Article,
(key, g) => new
{
Article= key,
Platforms = g.Select(p => p.Platform).ToList()
});
There are around 120 different Articles and about 30 different platforms, so the expected amount of items in group is around 120 yet I am recieving thousands of items. Items in record list are a lot as its the stock of all articles in the last 30 Days so I want to get a distinct list of Articles. I just can't figure out where to do this. what am I missing?
Edit:
After further inspecting the Data at runtime I just noticed that I have it backwards. the Articles are already correctly grouped, the platforms are the ones that need to be distinct, like Astrid E was guessing in the comments
CodePudding user response:
You can return distinct values of the Platform
collection by using Enumerable.Distinct()
.
The Platforms
value in the result selector in your .GroupBy()
operation should be computed as follows:
Platforms = g.Select(p => p.Platform).Distinct().ToList()
CodePudding user response:
Maybe you could try something like this:
var group = recordList.GroupBy(r => r.Article)
.Select(a =>
new
{
Article = a.Key,
Platforms = a.GroupBy(g => g.Platform)
});