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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1385421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:54:50  来源:igfitidea点击:

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

c#arraysdictionary

提问by leora

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?

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

采纳答案by Jon Skeet

Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable<T>) into a dictionary:

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

var dictionary = sequence.ToDictionary(item => item.Key,
                                       item => item.Value)

where Keyand Valueare 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.

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

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);

回答by Andrew Bullock

What do you mean?

你的意思是?

A dictionary is a hash, where keys map to values.

字典是一个散列,其中键映射到值。

What are your keys and what are your values?

你的关键是什么,你的价值观是什么?

foreach(var entry in myStringArray)
    myDictionary.Add(????, entry);

回答by Ronald Wildenberg

You can use LINQ to do this, but the question that Andrew asks should be answered first (what are your keys and values):

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

using System.Linq;

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

The result is a dictionary like this:

结果是这样的字典:

A -> A
B -> B
C -> C

回答by Kobi

If you need a dictionary without values, you might need a HashSet:

如果你需要一个没有值的字典,你可能需要一个HashSet

var hashset = new HashSet<string>(stringsArray);

回答by shA.t

IMO, When we say an Arraywe are talking about a list of values that we can get a value with calling its index (value => array[index]), So a correct dictionary is a dictionary with a key of index.

IMO,当我们说 an 时,Array我们谈论的是一个值列表,我们可以通过调用其索引 (value => array[index]) 来获取值,因此正确的字典是具有索引键的字典。

And with thanks to @John Skeet, the proper way to achieve that is:

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

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


Another way is to use an extension method like this:

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

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);
}

回答by Dwizzle

            Dictionary<int, string> dictionaryTest = new Dictionary<int, string>();

            for (int i = 0; i < testArray.Length; i++)
            {
                dictionaryTest.Add(i, testArray[i]);
            }

            foreach (KeyValuePair<int, string> item in dictionaryTest)
            {


                Console.WriteLine("Array Position {0} and Position Value {1}",item.Key,item.Value.ToString()); 
            }

回答by Vinod Srivastav

The Question is not very clear, but Yes you can convert a string to Dictionaryprovided the string is delimited with some characters to support Dictionary<Key,Value>pair

问题不是很清楚,但是是的,您可以将字符串转换为Dictionary提供字符串以一些字符分隔以支持Dictionary<Key,Value>

So if a string is like a=first;b=second;c=third;d=fourthyou can split it first based on ;then on =to create a Dictionary<string,string>the below extension method does the same

所以如果一个字符串就像 a=first;b=second;c=third;d=fourth你可以先根据;然后=创建一个Dictionary<string,string>下面的扩展方法来拆分它

public static Dictionary<string, string> ToDictionary(this string stringData, char propertyDelimiter = ';', char keyValueDelimiter = '=')
{
    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
    Array.ForEach<string>(stringData.Split(propertyDelimiter), s =>
        {
            keyValuePairs.Add(s.Split(keyValueDelimiter)[0], s.Split(keyValueDelimiter)[1]);
        });

    return keyValuePairs;
}

and can use it like

并且可以像这样使用它

var myDictionary = "a=first;b=second;c=third;d=fourth".ToDictionary();

since the default parameter is ;& =for the extension method.

因为扩展方法的默认参数是;& =

回答by Bill Stanton

I'll assume that the question has to do with arrays where the keys and values alternate. I ran into this problem when trying to convert redis protocol to a dictionary.

我假设这个问题与键和值交替的数组有关。我在尝试将 redis 协议转换为字典时遇到了这个问题。

private Dictionary<T, T> ListToDictionary<T>(IEnumerable<T> a)
{
    var keys = a.Where((s, i) => i % 2 == 0);
    var values = a.Where((s, i) => i % 2 == 1);
    return keys
        .Zip(values, (k, v) => new KeyValuePair<T, T>(k, v))
        .ToDictionary(kv => kv.Key, kv => kv.Value);
}