最优雅的方式将字符串数组转换为字典字典 [英] Most elegant way to convert string array into a dictionary of strings
问题描述
假设您正在使用.NET 3.5,您可以将任何序列(即 IEnumerable< T>
)转换为字典:
var dictionary = sequence.ToDictionary(item => item.Key,
item => item.Value)
其中键
和值
是要作为键和值的适当属性。您可以指定一个用于键的投影,如果项目本身是您想要的值。
所以例如,如果你想映射大写每个字符串的版本到原始,可以使用:
var dictionary = strings.ToDictionary(x => x.ToUpper ());
在你的情况下,你想要的是什么键和值?
如果你实际上只想要一个集(你可以检查它是否包含一个特定的字符串,例如),你可以使用:
var words = new HashSet< string>(listOfStrings);
Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?
Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable<T>
) into a dictionary:
var dictionary = sequence.ToDictionary(item => item.Key,
item => item.Value)
where Key
and Value
are the appropriate properties you want to act as the key and value. You can specify just one projection which is used for the key, if the item itself is the value you want.
So for example, if you wanted to map the upper case version of each string to the original, you could use:
var dictionary = strings.ToDictionary(x => x.ToUpper());
In your case, what do you want the keys and values to be?
If you actually just want a set (which you can check to see if it contains a particular string, for example), you can use:
var words = new HashSet<string>(listOfStrings);
这篇关于最优雅的方式将字符串数组转换为字典字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!