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

后端 未结 8 1004
没有蜡笔的小新
没有蜡笔的小新 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 ToDictionary(this IEnumerable array)
    {
        return array
            .Select((v, i) => new {Key = i, Value = v})
            .ToDictionary(o => o.Key, o => o.Value);
    }
    

提交回复
热议问题