C#转换列表< string>到字典< string,string> [英] C# Convert List<string> to Dictionary<string, string>

查看:581
本文介绍了C#转换列表< string>到字典< string,string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一件奇怪的事情,但是忽略这一点,是否有一个很好的简洁的方法来转换列表到字典,其中每个键值对在字典中只是列表中的每个字符串。即

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.

List = string1, string2, string3
Dictionary = string1/string1, string2/string2, string3/string3

我已经做了大量的搜索,而在Stackoverflow中只有几十个例子,在相反的情况下方向,但不是这样。

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.

这样做的原因是我有两个第三部分组件,改变它们是我的手中。一个返回作为列表的电子邮件地址列表,另一个发送电子邮件,其中To参数是Dictionary。字典的关键是电子邮件地址,值是他们的真实姓名。但是,我不知道真实姓名,但是如果您将真实姓名设置为电子邮件地址,它仍然可以工作。所以为什么我想把一个列表转换成一个字典。有很多方法可以做到这一点。列表中的foreach循环将一个kvp添加到字典。但是我喜欢简洁的代码,并想知道是否有单行解决方案。

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.

推荐答案

尝试这个:

var res = list.ToDictionary(x => x, x => x);

第一个lambda可以让您选择该键,第二个选择该值。

The first lambda lets you pick the key, the second one picks the value.

您可以使用它,使值与键不同,如下所示:

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));

如果您的列表包含重复项,请添加 Distinct()像这样:

If your list contains duplicates, add Distinct() like this:

var res = list.Distinct().ToDictionary(x => x, x => x);

编辑要评论有效的原因,我认为唯一的原因可能对转换有效,就像这样,在某些时候,关键字和结果字典中的值将会分歧。例如,您将进行初始转换,然后使用其他值替换某些值。如果密钥和值始终相同, HashSet< String> 将提供更好的适合您的情况: p>

EDIT To 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 always going to be the same, HashSet<String> would provide a much better fit for your situation:

var res = new HashSet<string>(list);
if (res.Contains("string1")) ...

这篇关于C#转换列表&lt; string&gt;到字典&lt; string,string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆