Kai
Kai

Reputation: 790

Receiving an unclear error when using SelectMany() on an IGrouping

When I write the following code I get the error:

the type argument for method Enumerable.SelectMany cannot be inferred from usage

var model = new Overview()
{
   ModelData = data.GroupBy(g => g.GroupingId1).Select(s => new OverviewdataGrouped()
   {
       Id = s.Key,
       Grouping = s.GroupBy(gr => gr.GroupingId2). Select(se => new OverviewdataGroupedFurther()
       {
           Id= se.Key,
           Grouping2 = se.Any() ? se.SelectMany(sel => sel).ToList() : new List<DataModel>()
       })
   })
};

As far as I know this is how I always selected the data from an IGrouping, but for some reason it is not working this way. Does anyone know what I am missing or what the problem could be?

(Note that the variable sel within the SelectMany contains the correct type (DataModel))

Upvotes: 0

Views: 111

Answers (1)

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14595

The SelectMany Method projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

Your usage of the SelectMany method seems redundant, since se is the result of a grouping operation. Try replacing this:

se.SelectMany(sel => sel).ToList()

By This:

se.ToList()

Upvotes: 2

Related Questions