考虑以下目标:
class Menu{
public int Section {get; set;}
public string Parent {get; set;}
public string Name {get; set;}
public string Url {get; set;}
/* more */
}我正在获取这些对象的列表,我希望将它们按节分组,然后在每个部分中按父类对它们进行分组,所以我使用了以下结构:
ILookup<int, ILookup<string, Menu>> MenuStructure =
menuList.ToLookup(m => m.Section, menuList.ToLookup(m => m.Parent));但我发现了一个错误:
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?)
我做错了什么?
发布于 2019-05-23 07:57:55
您需要首先添加一个分组.GroupBy():
ILookup<int, ILookup<string, Menu>> MenuStructure =
menuList.GroupBy(m => m.Section).ToLookup(g => g.Key, v => v.ToLookup(m => m.Parent));否则,内部.ToLookup作用于整个列表,而不是第一个.ToLookup提供的列表。
.net小提琴的完整代码:
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));
}
}https://stackoverflow.com/questions/31070930
复制相似问题