Convert a C# string array to a dictionary

前端 未结 7 1794
死守一世寂寞
死守一世寂寞 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:46

    public static IEnumerable EveryOther(this IEnumerable source)
    {
        bool shouldReturn = true;
        foreach (T item in source)
        {
            if (shouldReturn)
                yield return item;
            shouldReturn = !shouldReturn;
        }
    }
    
    public static Dictionary MakeDictionary(IEnumerable source)
    {
        return source.EveryOther()
            .Zip(source.Skip(1).EveryOther(), (a, b) => new { Key = a, Value = b })
            .ToDictionary(pair => pair.Key, pair => pair.Value);
    }
    

    The way this is set up, and because of the way Zip works, if there are an odd number of items in the list the last item will be ignored, rather than generation some sort of exception.

    Note: derived from this answer.

提交回复
热议问题