从列表创建查找

时间:2017-02-21 05:14:03

标签: c#

我想从列表中创建Lookup

List<User> users = new List<User>() { new User() { id = "1", code = "a" },
                                      new User() {id="2", code= "a" },
                                      new User() {id="3", code= "a" },
                                      new User() {id="4", code= "b" },
                                      new User() {id="1", code= "b" }
            };

我写的代码是

Lookup<string, string> lkup = (Lookup<string, string>)users.ToLookup(k => k.id, k => k.code);

尽管如此,我最终得到了一个Lookup,我无法找到这些值。

其次,我不明白为什么我无法使用类似

的内容创建Lookup
Lookup<string, string> lkup = users.ToLookup<string,string>(

1 个答案:

答案 0 :(得分:0)

您原始代码中的值就在那里。在枚举它们之前,您无法看到它们。以下内容将在下一行打印每个键后跟其值:

List<User> users = new List<User>() { new User() { id = "1", code = "a" },
                          new User() {id="2", code= "a" },
                          new User() {id="3", code= "a" },
                          new User() {id="4", code= "b" },
                          new User() {id="1", code= "b" }
};
Lookup<string, string> lkup = (Lookup<string,string>)users.ToLookup(x => x.id, x => x.code);
foreach(var k in lkup)
{
    Console.WriteLine(k.Key);
    foreach(var v in k)
    {
        Console.Write($"{v} ");
    }
    Console.WriteLine();
}

此:

Lookup<string, string> lkup = users.ToLookup<string,string>(k => k.id, k => k.code);

无效,因为lkup必须是ILookup而不是Lookup

ILookup<string, string> lkup = users.ToLookup(k => k.id, k => k.code);

将生成与投射到Lookup相同的内容。

这是我用于列表的类:

class User
{
    public string id = "";
    public string code = "";
}