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

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

问题描述

是否有将字符串数组转换为字符串字典的内置函数,或者您需要在这里做一个循环?

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?

推荐答案

假设您使用的是 .NET 3.5,您可以将任何序列(即 IEnumerable)转换为字典:

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)

其中 KeyValue 是您想要用作键和值的适当属性.如果项目本身就是您想要的值,您可以只指定一个用于键的投影.

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?

如果您实际上只想要一个 set(例如,您可以检查它是否包含特定字符串),您可以使用:

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天全站免登陆