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

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

问题描述

解决方案

div>

假设您正在使用.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屋!

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