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

leo*_*ora 42 c# arrays dictionary

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

Jon*_*eet 84

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

var dictionary = sequence.ToDictionary(item => item.Key,
                                       item => item.Value)
Run Code Online (Sandbox Code Playgroud)

在哪里Key和哪个Value是您想要充当关键和值的适当属性.如果项目本身是您想要的值,则只能指定一个用于键的投影.

例如,如果您想将每个字符串的大写版本映射到原始字符串,您可以使用:

var dictionary = strings.ToDictionary(x => x.ToUpper());
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您希望键和值是什么?

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

var words = new HashSet<string>(listOfStrings);
Run Code Online (Sandbox Code Playgroud)


Ron*_*erg 15

您可以使用LINQ来执行此操作,但应首先回答Andrew要求的问题(您的键和值是什么):

using System.Linq;

string[] myArray = new[] { "A", "B", "C" };
myArray.ToDictionary(key => key, value => value);
Run Code Online (Sandbox Code Playgroud)

结果是这样的字典:

A -> A
B -> B
C -> C
Run Code Online (Sandbox Code Playgroud)


shA*_*A.t 7

IMO,当我们说一个Array值列表时,我们可以通过调用它的索引(值=> array [index])获得一个值,因此正确的字典就是带有索引键的字典。

感谢@John Skeet,实现这一目标的正确方法是:

var dictionary = array
    .Select((v, i) => new {Key = i, Value = v})
    .ToDictionary(o => o.Key, o => o.Value);
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用这样的扩展方法:

public static Dictionary<int, T> ToDictionary<T>(this IEnumerable<T> array)
{
    return array
        .Select((v, i) => new {Key = i, Value = v})
        .ToDictionary(o => o.Key, o => o.Value);
}
Run Code Online (Sandbox Code Playgroud)

  • 这将 a) 效率低下;b) 如果相同的值在数组中出现多次,则失败。您可以使用也提供索引的“Select”重载,以更有效、更可靠地执行此操作。 (2认同)

Kob*_*obi 5

如果您需要没有值的字典,则可能需要HashSet:

var hashset = new HashSet<string>(stringsArray);
Run Code Online (Sandbox Code Playgroud)