Convert a C# string array to a dictionary

前端 未结 7 1795
死守一世寂寞
死守一世寂寞 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:35
    a.Select((input, index) = >new {index})
      .Where(x=>x.index%2!=0)
      .ToDictionary(x => a[x.index], x => a[x.index+1])
    

    I would recommend using a for loop but I have answered as requested by you.. This is by no means neater/cleaner..

    0 讨论(0)
  • 2021-01-07 06:37
    IEnumerable<string> strArray = new string[] { "name", "Fred", "colour", "green", "sport", "tennis" };
    
    
                var even = strArray.ToList().Where((c, i) => (i % 2 == 0)).ToList();
                var odd = strArray.ToList().Where((c, i) => (i % 2 != 0)).ToList();
    
                Dictionary<string, string> dict = even.ToDictionary(x => x, x => odd[even.IndexOf(x)]);
    
    0 讨论(0)
  • 2021-01-07 06:43

    Since it's an array I would do this:

    var result = Enumerable.Range(0,a.Length/2)
                           .ToDictionary(x => a[2 * x], x => a[2 * x + 1]);
    
    0 讨论(0)
  • 2021-01-07 06:46
    public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
    {
        bool shouldReturn = true;
        foreach (T item in source)
        {
            if (shouldReturn)
                yield return item;
            shouldReturn = !shouldReturn;
        }
    }
    
    public static Dictionary<T, T> MakeDictionary<T>(IEnumerable<T> 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.

    0 讨论(0)
  • 2021-01-07 06:48
    var dict = a.Select((s, i) => new { s, i })
                .GroupBy(x => x.i / 2)
                .ToDictionary(g => g.First().s, g => g.Last().s);
    
    0 讨论(0)
  • 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<T, T2> ZipMyTwoListToDictionary<T, T2>(IEnumerable<T> listContainingKeys, IEnumerable<T2> listContainingValue)
        {
            return listContainingValue.Zip(listContainingKeys, (value, key) => new { value, key }).ToDictionary(i => i.key, i => i.value);
        }
    
    0 讨论(0)
提交回复
热议问题