user2906420
user2906420

Reputation: 1269

How to use groupby in linq sql

I am trying to group a list and using ToDictionary to achieve this which works:

var levels = ids.GroupBy(f => f.Id).
    ToDictionary(g => g.Key, g => g.First().Name);

The problem is: in the string "Name" the last char is a number i.e. 2 or 5 or 7 etc.

I do NOT want to select the first but I want to select "Name" with the MAX number. How can i achieve this. example of Name can be: "abd-hbb-les3" , "abd-hbb-les1" , "abd-hbb-les6"

Upvotes: 0

Views: 77

Answers (2)

Paweł Bejger
Paweł Bejger

Reputation: 6366

You could do this in the following way:

var levels = ids.GroupBy(f => f.Id).ToDictionary(g => g.Key, 
    g => g.First( x=> x.Name.Last() == g.Max( y=> y.Name.Last())).Name);

assuming that it's really about the last letter so it's not possible to have a two (or more) digits at the end e.g.:

abd-hbb-les16 //will not work with the above code

Upvotes: 2

i3arnon
i3arnon

Reputation: 116518

For every group simply select the name with the maximum last character of the string. Like this:

var levels = ids.
    GroupBy(f => f.Id).
    ToDictionary(
        g => g.Key,
        g => g.First(i => i.Name.Last() == g.Max(j => j.Name.Last())).Name);

Upvotes: 1

Related Questions