简体   繁体   English

将字符串数组转换为字符串字典的最优雅方法

[英]Most elegant way to convert string array into a dictionary of strings

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?是否有内置的 function 用于将字符串数组转换为字符串字典,还是需要在这里进行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

是否有将字符串数组转换为字符串字典的内置函数,还是需要在此处执行循环?

You can create a dictionary from an IEnumerable<T> , including an array, via:您可以通过以下方式从IEnumerable<T> (包括数组)创建字典:

var dictionary = myEnumerable.ToDictionary(element => element.Key,
                                           element => element.Value)

where Key and Value are the key and value you want to store in each dictionary element.其中KeyValue是要存储在每个字典元素中的键和值。 Available in .NET Framework 3.5+/.NET Core 1.0+/.NET 5.0+.在 .NET 框架 3.5+/.NET Core 1.0+/.NET 5.0+ 中可用。 Official documentation. 官方文档。

If you want the dictionary values to be the elements from the original enumerable:如果您希望字典是原始可枚举的元素:

   var dictionary = myEnumerable.ToDictionary(element => element.Key)

If you only need high-performance set operations, you may be able to use:如果只需要高性能的集合操作,或许可以使用:

var words = new HashSet<string>(listOfStrings);

In simple terms, the HashSet class can be thought of as a Dictionary<TKey,TValue> collection without values.简单来说,HashSet class 可以被认为是一个没有值的 Dictionary<TKey,TValue> 集合。 Official documentation. 官方文档。

(Note that a 'sequence' in an entirely unrelated object. Originally submitted an existing answer edit but it was rejected by the author so posting separately, including with links to the official Microsoft documentation.) (请注意, 完全不相关的 object 中的“序列”。最初提交了一个现有的答案编辑,但被作者拒绝,因此单独发布,包括指向微软官方文档的链接。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM