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

后端 未结 8 983
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:39

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?

相关标签:
8条回答
  • 2020-12-08 19:26

    IMO, When we say an Array we 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.

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

    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);
    }
    
    0 讨论(0)
  • 2020-12-08 19:31

    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.

    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);
    }
    
    0 讨论(0)
提交回复
热议问题