且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

最优雅的方式,以字符串数组转换成字符串的字典

更新时间:2023-02-03 08:34:06

假设你正在使用.NET 3.5,你可以将任何序列(即的IEnumerable< T> )转换成字典:

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