Nested ILookup - Argument ype error

311 Views Asked by At

Consider the following object:

class Menu{
    public int Section {get; set;}
    public string Parent {get; set;}
    public string Name {get; set;}
    public string Url {get; set;}
    /* more */
}

I am getting a list of these objects and I want to group them by section and then inside each section I want to group them by parent so I used the following structure:

ILookup<int, ILookup<string, Menu>> MenuStructure = 
         menuList.ToLookup(m => m.Section, menuList.ToLookup(m => m.Parent));

but I'm getting this error:

Cannot implicitly convert type 'System.Linq.ILookup<int,MyNamespace.Menu>' to 'System.Linq.ILookup<int,System.Linq.ILookup<string,MyNamespace.Menu>>'. An explicit conversion exists (are you missing a cast?)

What am I doing wrong?

1

There are 1 best solutions below

0
On

You need to add a grouping .GroupBy() first:

ILookup<int, ILookup<string, Menu>> MenuStructure = 
        menuList.GroupBy(m => m.Section).ToLookup(g => g.Key, v => v.ToLookup(m => m.Parent));

otherwise the inner .ToLookup acts on the whole list, not the list provided by the first .ToLookup

Full code for a .net fiddle:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    class Menu {
      public int Section {get; set;}
      public string Parent {get; set;}
      public string Name {get; set;}
      public string Url {get; set;}
    }

    public static void Main()
    { 
        var menuList = new List<Menu>();

        ILookup<int, ILookup<string, Menu>> MenuStructure = 
             menuList.GroupBy(m => m.Section).ToLookup(g => g.Key, v => v.ToLookup(m => m.Parent));
    }
}