Michael Sandler
Michael Sandler

Reputation: 1309

Ordered grouping without Dictionary

I am grouping train trips according to the coal mines they service, and then dealing with the each group starting with the most populous.

List<List<Trip>> tripsByMine = trips.GroupBy(x => x.demand.Mine)
                                    .ToDictionary(x => x.Key, x => x.ToList())
                                    .Values.OrderByDescending(x => x.Count)
                                    .ToList();

It seems to me that the ToDictionary call is superfluous because I just want the Values. Is there a shorter way of getting the same result?

Upvotes: 0

Views: 54

Answers (2)

Andrea Scarcella
Andrea Scarcella

Reputation: 3323

Possible solution:

    List<List<Trip>> tripsByMine = trips.GroupBy(x => x.demand.Mine)
                                        .Select(x => new {Key=x.Key, Values=x,Count=x.Count()})
                                        .OrderByDescending(x => x.Count)
.Select(x=>x.Values.ToList())
                                        .ToList();

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

Try this

List<List<Trip>> tripsByMine2 = trips.GroupBy(x => x.demand.Mine)
    .Select(x => x.ToList())
     .OrderByDescending(x => x.Count)
     .ToList();

Upvotes: 2

Related Questions