Accepted answer

First of all when you are using GroupBy function, var is compiled to:


If you really want to have List<List<testobject>> you can use this query:

testobjectList.Where(x => x.field1 >= 2).GroupBy(x => x.field2).Select(x => x.ToList()).ToList();

And if you want to have List<testobject> you can use:

testobjectList.Where(x => x.field1 >= 2).GroupBy(x => x.field2).Select(x => x.First()).ToList();


List<List<testobject>> wouldn't be the correct type. If you added a breakpoint on a line after and results1 is declared and inspected the type of it you would probably see something similar to List<IGrouping<string, testobject>>. If you want to declare explicit types use some means to figure out actual type, like a debugger, IDE or some plugin. ReSharper could give you a refactoring option to declare explicit type instead of var.


When you hover over the ToList() call in VisualStudio you can see that the return type is List<IGrouping<string, testobject>>


List<IGrouping<string, testobject>> results2 = testobjectList.Where(x => x.field1 >= 2)
                                                             .GroupBy(x => x.field2).ToList();

If you have ReSharper you can use the "Specify type explicitly" refactoring to convert the var statement to the explicit type.


You need to flatten your result by adding a .SelectMany() to strongly type the result as a List.

You also have the List declared as List<List> result 2 when it should be List

Working Sample:

List<testobject> results2 = testobjectList .Where(x => x.field1 >= 2)

Related Query

More Query from same tag