最优雅的方式,以字符串数组转换成字符串的字典 [英] most elegant way to convert string array into a dictionary of strings

查看:223
本文介绍了最优雅的方式,以字符串数组转换成字符串的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个内置的功能,这个还是需要在这里做一个循环。

is there a built in function for this or do you need to do a loop here.

推荐答案

假设你正在使用.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);

这篇关于最优雅的方式,以字符串数组转换成字符串的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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