C# 使用 linq 填充字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15324282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:25:53 来源:igfitidea点击:
populate a dictionary using linq
提问by Bick
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.
How do I do that?
Thanks.
我想使用 LINQ 填充字典。
我怎么做?谢谢。
采纳答案by MarcinJuraszek
appTypeMap = allApplicationTypes.ToDictionary(x => x.id, x => x.name);
However, it will create a new dictionary, not fill yours.
但是,它会创建一个新字典,而不是填充您的字典。
回答by Mike C.
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() ......