0

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.

Herrozerro
  • 1,601
  • 1
  • 22
  • 37
  • as I understood correctly, just turn .Select(x => x.Key) into .Select(x => x.ToList()) – Victor Apr 16 '15 at 23:30
  • also, i / 3 will break your collection into 3 pieces, to partition by length you may look at answer http://stackoverflow.com/questions/5215469/use-linq-to-break-up-listt-into-lots-of-listt-of-n-length#5215506 – Victor Apr 16 '15 at 23:36
  • @Victor, that is what I'd like. At least for now I'd like to just simply break into groups of three when it is sorted by length. – Herrozerro Apr 17 '15 at 12:10

2 Answers2

2

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

david.s
  • 11,283
  • 6
  • 50
  • 82
  • I would add to this that he probably wants `.GroupBy(x => x.Grouping, x => x.Item)`. This will produce a list of lists of `a`s, whereas what he's got now will produce a list of lists of objects of that anonymous type created in the first `Select()`. – Joe Farrell Apr 16 '15 at 23:32
0

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();   
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68