C# 使用LINQ将此列表转换为字典

C# 使用LINQ将此列表转换为字典,c#,linq,dictionary,C#,Linq,Dictionary,我有一门课: public class Client { public Client() { TemplateKeys = new List<int>(); } public List<int> TemplateKeys { get; set; } } 现在我想让这个LINQ表达式返回所需的Dictionary结果。我看到LINQ内置了ToDictionary()扩展方法,但我找不到一种方法,通过将ToList()替换为

我有一门课:

public class Client
{
    public Client()
    {
        TemplateKeys = new List<int>();
    }

    public List<int> TemplateKeys { get; set; }
}
现在我想让这个
LINQ
表达式返回所需的
Dictionary
结果。我看到
LINQ
内置了
ToDictionary()
扩展方法,但我找不到一种方法,通过将
ToList()
替换为
ToDictionary()
来获得结果,如下所示:

templatesInUse  = clients.SelectMany(cl => cl.TemplateKeys)
                         .Distinct()
                         .ToDictionary(//tried some things here with no success);
因此,我看到几乎所有带有
ToDictionary
的示例都使用
GroupBy()
,尽管我不需要分组,我希望看到不使用分组的解决方案,但我重新制作了
LINQ
如下:

templatesInUse = clients.SelectMany(cl => cl.TemplateKeys)
                        .Distinct()
                        .GroupBy(t => t)
                        .ToDictionary(g => g.Key, g.ToString());

这在某种程度上是有效的,但不是我想要的
字符串。空的
或只是
“”
value我得到了一些奇怪的值,这在理论上是可行的,因为这些值将被替换,但我仍然希望得到一个干净的值,我的意思是,在执行
LINQ
查询之后,我希望得到
TemplateKey
作为我的字典键,空字符串作为我的值。正如我所提到的,我真的很想知道并且希望看到一种不使用
GroupBy()
的方法,当使用
ToDictionary()
时,这是必须的吗?

您不需要分组。只需将键指定为数字,将值指定为
string.Empty.

templatesInUse = clients.SelectMany(cl => cl.TemplateKeys).Distinct()
                 .ToDictionary(x => x, x => string.Empty);

你不需要分组。只需将键指定为数字,将值指定为
string.Empty.

templatesInUse = clients.SelectMany(cl => cl.TemplateKeys).Distinct()
                 .ToDictionary(x => x, x => string.Empty);

Brr,谢谢你,这正是我在过去30分钟想要达到的。Brr,谢谢你,这正是我在过去30分钟想要达到的。
templatesInUse = clients.SelectMany(cl => cl.TemplateKeys)
                        .Distinct()
                        .GroupBy(t => t)
                        .ToDictionary(g => g.Key, g.ToString());
templatesInUse = clients.SelectMany(cl => cl.TemplateKeys).Distinct()
                 .ToDictionary(x => x, x => string.Empty);