Herrozerro
Herrozerro

Reputation: 1681

Select a group of n objects into a list of a list of objects

I have Object A in which I have lengths. I would like to order by length descending, then I would like to group them by threes and return that list of a list of objects.

I can get the grouping to work, but all i get is the key of the grouping and not the items.

public class a
{
    public string Id { get; set; }
    public int Length { get; set; }
}

List<a> c = Instantiate a list

c.OrderByDescending(x => x.Length)
.Select((e, i) => new { Item = e, Grouping = (i / 3) })
.GroupBy(x => x.Grouping)
.Select(x => x.Key)
.ToList()

I think it has something to do with my group by but I cant seem to get it to work. What I would like is a List<List<a>> that have at most three items.

Upvotes: 0

Views: 548

Answers (2)

PiotrWolkowski
PiotrWolkowski

Reputation: 8792

Following query will generate a list of lists where the inner list contains three items:

var listOfTriplets = c.OrderByDescending(x => x.Length)
    .Select((x, i) => new { Index = i, Value = x })
    .GroupBy(x => x.Index / 3)
    .Select(x => x.Select(v => v.Value).ToList())
    .ToList();   

Upvotes: 0

david.s
david.s

Reputation: 11403

Use this .Select(grp => grp.ToList()) instead of .Select(x => x.Key). This will return the group as a List<a>.

Upvotes: 2

Related Questions