Convert a C# string array to a dictionary

前端 未结 7 1793
死守一世寂寞
死守一世寂寞 2021-01-07 06:20

Is there an elegant way of converting this string array:

string[] a = new[] {\"name\", \"Fred\", \"colour\", \"green\", \"sport\", \"tennis\"};
7条回答
  •  别那么骄傲
    2021-01-07 06:49

    I've made a simular method to handle this type of request. But since your array contains both keys and values i think you need to split this first.

    Then you can use something like this to combine them

    public static IDictionary ZipMyTwoListToDictionary(IEnumerable listContainingKeys, IEnumerable listContainingValue)
        {
            return listContainingValue.Zip(listContainingKeys, (value, key) => new { value, key }).ToDictionary(i => i.key, i => i.value);
        }
    

提交回复
热议问题