C# 将 List<string> 转换为 Dictionary<string, string>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11581101/
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
C# Convert List<string> to Dictionary<string, string>
提问by Jonnster
This may seem an odd thing to want to do but ignoring that, is there a nice concise way of converting a List to Dictionary where each Key Value Pair in the Dictionary is just each string in the List. i.e.
这可能看起来很奇怪,但忽略这一点,是否有一种将列表转换为字典的简洁方法,其中字典中的每个键值对只是列表中的每个字符串。IE
List = string1, string2, string3
Dictionary = string1/string1, string2/string2, string3/string3
I have done plenty of searching and there are literally dozens of examples on Stackoverflow alone of doing it in the opposite direction but not this way round.
我已经进行了大量搜索,仅在 Stackoverflow 上就有数十个示例,它们以相反的方向进行,但并非如此。
The reason for doing this is I have two third part components and changing them is out of my hands. One returns a list of email addresses as a List and the other sends emails where the To parameter is a Dictionary. The key of the dictionary is the email address and the value is their real name. However, I don't know the real name but it still works if you set the real name to the email address as well. Therefore why I want to convert a List to a Dictionary. There are plenty of ways of doing this. A foreach loop on the list which adds a kvp to a dictionary. But I like terse code and wondered if there was a single line solution.
这样做的原因是我有两个第三方组件,更改它们是我无法控制的。一个返回电子邮件地址列表作为列表,另一个发送电子邮件,其中 To 参数是一个字典。字典的键是电子邮件地址,值是他们的真实姓名。但是,我不知道真实姓名,但如果您将真实姓名也设置为电子邮件地址,它仍然有效。因此,为什么我想将列表转换为字典。有很多方法可以做到这一点。列表上的 foreach 循环将 kvp 添加到字典中。但我喜欢简洁的代码,想知道是否有单行解决方案。
采纳答案by dasblinkenlight
Try this:
尝试这个:
var res = list.ToDictionary(x => x, x => x);
The first lambda lets you pick the key, the second one picks the value.
第一个 lambda 使您可以选择键,第二个 lambda 可以选择值。
You can play with it and make values differ from the keys, like this:
您可以使用它并使值与键不同,如下所示:
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));
If your list contains duplicates, add Distinct()like this:
如果您的列表包含重复项,请按以下方式添加Distinct():
var res = list.Distinct().ToDictionary(x => x, x => x);
EDITTo comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are alwaysgoing to be the same, HashSet<String>would provide a much better fit for your situation:
编辑为了评论正当理由,我认为对这样的转换有效的唯一原因是,在某些时候,结果字典中的键和值会出现分歧。例如,您将进行初始转换,然后将某些值替换为其他值。如果键和值始终相同,HashSet<String>将更适合您的情况:
var res = new HashSet<string>(list);
if (res.Contains("string1")) ...
回答by Daniel Hilgarth
Use this:
用这个:
var dict = list.ToDictionary(x => x);
See MSDNfor more info.
有关更多信息,请参阅MSDN。
As Pranay points out in the comments, this will fail if an item exists in the list multiple times.
Depending on your specific requirements, you can either use var dict = list.Distinct().ToDictionary(x => x);to get a dictionary of distinct items or you can use ToLookupinstead:
正如 Pranay 在评论中指出的那样,如果一个项目在列表中多次存在,这将失败。
根据您的特定要求,您可以使用var dict = list.Distinct().ToDictionary(x => x);来获取不同项目的字典,也可以使用ToLookup:
var dict = list.ToLookup(x => x);
This will return an ILookup<string, string>which is essentially the same as IDictionary<string, IEnumerable<string>>, so you will have a list of distinct keys with each string instance under it.
这将返回一个ILookup<string, string>本质上与 相同的IDictionary<string, IEnumerable<string>>,因此您将拥有一个不同键的列表,其中包含每个字符串实例。
回答by Lukazoid
By using ToDictionary:
通过使用ToDictionary:
var dictionary = list.ToDictionary(s => s);
If it is possible that any string could be repeated, either do a Distinctcall first on the list (to remove duplicates), or use ToLookupwhich allows for multiple values per key.
如果任何字符串都可能重复,Distinct请先在列表上调用(以删除重复项),或者使用ToLookup它允许每个键有多个值。
回答by Pranay Rana
EDIT
编辑
another way to deal with duplicate is you can do like this
处理重复的另一种方法是你可以这样做
var dic = slist.Select((element, index)=> new{element,index} )
.ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);
or
或者
easy way to do is
简单的方法是
var res = list.ToDictionary(str => str, str=> str);
but make sure that there is no string is repeating...again otherewise above code will not work for you
但请确保没有重复的字符串...再说一遍,上面的代码对您不起作用
if there is string is repeating than its better to do like this
如果有字符串重复比这样做更好
Dictionary<string,string> dic= new Dictionary<string,string> ();
foreach(string s in Stringlist)
{
if(!dic.ContainsKey(s))
{
// dic.Add( value to dictionary
}
}
回答by dtsg
You can use:
您可以使用:
var dictionary = myList.ToDictionary(x => x);

