0
class SomeObject
{
     int Value { get; set; }
     string ID { get; set; }
}

var TheList = List<SomeObject> { ... }

var groupedObjects = TheList.GroupBy(o => o.ID);

The return type is IEnumerable<IGrouping<SomeObject, string, SomeObject>> In the Debug "Results View" the Items are grouped correctly.

How can I get List<List<SomeObject>> as return?

A simple ToList() does obviously not work.

2 Answers2

3

You need two ToList()s:

TheList.GroupBy(o => o.ID, c => c)
       .Select(g=>g.ToList())
       .ToList();
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 2
    Nit: I think you can drop the `c => c`? Although granted it is in OP's question – canton7 Dec 16 '20 at 17:36
  • @canton7 Yes it could be removed, but it doesn't change anything and leaves the original attempt intact (the relevant change is the addition of the `ToList()`s) – D Stanley Dec 16 '20 at 17:47
  • Thanks to you both. c was indeed unnecessary but how @DStanley mentioned it doesn't change the result. – NoName1248 Dec 16 '20 at 17:51
-1

Here's a similar question with good answers: How to get values from IGrouping

You could try

var groupedObjects = TheList.GroupBy(o => o.ID, c => c).SelectMany();
catfood
  • 4,267
  • 5
  • 29
  • 55
  • 1
    1) There's no parameterless version of `SelectMany` (so this won't compile), and 2) I'm not sure that this is what they're after: `SelectMany(x => x)` will flatten the groupings out into a single level, whereas OP still wants two levels, they just want them both to be lists – canton7 Dec 16 '20 at 17:35