I have list of records, each record has Name and Rounds. Rounds is a concatenated numbers seperated by "-"
How can i group by name and display only unique rounds, also count the number of rounds and display the first round and last round
Here is what i tried,
data.GroupBy(d => d.Name)
.Select(
g => new
{
Name = g.Key,
Rounds = g.Concat(s => s.Rounds),
NumberOfRounds = g.Concat(s => s.Rounds).Split('-').Count,
FirstRound = //??,
LastRound = //??,
});
I would start by projecting your entity to a name and collection-of-rounds pair. That will then be easier to work with. For example:
var query = results
.Select(d => new { d.Name, Results = d.Rounds.Split('-').Select(int.Parse).ToList() })
.GroupBy(
d => d.Name, (key, values) => new {
Name = key,
Rounds = values.SelectMany(v => v.Rounds)
.Distinct()
.OrderBy(x => x)
.ToList()
});
With the rounds available as a list, I don't see that there's much point in having NumberOfRounds
, FirstRound
and LastRound
as properties, as you can just use Rounds.Count
, Rounds.First()
, Rounds.Last()
. The important part is transforming the data into a more useful format as early as possible.
If you really need that in properties, it's easy enough to project:
// query as before, but with
.Select(x => new {
x.Name,
x.Rounds,
NumberOfRounds = x.Rounds.Count,
FirstRound = x.Rounds.First(),
LastRound = x.Rounds.Last()
});
See more on this question at Stackoverflow