Linq group returns a unique group

I have a list of entries, each entry has a Name and Rounds . Rounds are concatenated numbers separated by a "-"

enter image description here

How can I group by name and display only unique rounds, also calculate the number of rounds and display the first round and the last round

enter image description here

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 = //??,
    });
+4
source share
2 answers

I would start by projecting your entity onto a couple of names and a collection of rounds. It will be easier to work with. For instance:

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()
       });

, , , NumberOfRounds, FirstRound LastRound , Rounds.Count, Rounds.First(), Rounds.Last(). - .

, :

// query as before, but with
.Select(x => new {
    x.Name,
    x.Rounds,
    NumberOfRounds = x.Rounds.Count,
    FirstRound = x.Rounds.First(),
    LastRound = x.Rounds.Last()
});
+5

. .

var data = ...;
var groupedData = data
    .GroupBy(x => x.Name)
    .Select(x => new {
        Name = x.Key,
        Rounds = string.Join("-", x.Select(z => z.Rounds))
            .Split('-')
            .Distinct()
            .Select(z => int.Parse(z))
            .OrderBy(z => z)
            .ToArray()
    })
    .Select(x => new {
        x.Name,
        Rounds = string.Join("-", x.Rounds),
        NumberOfRounds = x.Length,
        FirstRound = x.Min(),
        LastRound = x.Max()
    })
    .ToArray();
+1

All Articles