简体   繁体   English

使用linq填充字典

[英]populate a dictionary using linq

I have the following empty Dictionary 我有以下空字典

Dictionary<Guid, string> appTypeMap = new Dictionary<Guid, string>();

and the following list: 以下列表:

List<ApplicationType> allApplicationTypes = _applicationTypeService.GetAll()

Application type is described as follows: 应用程序类型描述如下:

public class ApplicationType
{
   public Guid id {get; set;}
   public String name {get; set;}
}

I want to populate the dictionary using LINQ. 我想使用LINQ填充字典。
How do I do that? 我怎么做? Thanks. 谢谢。

appTypeMap = allApplicationTypes.ToDictionary(x => x.id, x => x.name);

但是,它会创建一个新词典,而不是填写你的词典。

Try 尝试

appTypeMap = _applicationTypeService.GetAll().Select(o => new DictionaryEntry{
  Key = o.id,
  Value = o.name
}).ToList();

Not sure if you need a .ToList() on the end.... 不确定你是否需要一个.ToList()....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM