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.

3
  • as I understood correctly, just turn .Select(x => x.Key) into .Select(x => x.ToList()) Commented Apr 16, 2015 at 23:30
  • also, i / 3 will break your collection into 3 pieces, to partition by length you may look at answer stackoverflow.com/questions/5215469/… Commented Apr 16, 2015 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. Commented Apr 17, 2015 at 12:10

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would add to this that he probably wants .GroupBy(x => x.Grouping, x => x.Item). This will produce a list of lists of as, whereas what he's got now will produce a list of lists of objects of that anonymous type created in the first Select().
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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.