【问题标题】:Convert a C# string array to a dictionary将 C# 字符串数组转换为字典
【发布时间】:2012-09-07 17:25:47
【问题描述】:

有没有一种优雅的方式来转换这个字符串数组:

string[] a = new[] {"name", "Fred", "colour", "green", "sport", "tennis"};

放入字典,使得数组的每两个连续元素成为字典的一个 {key, value} 对(我的意思是 {"name" -> "Fred", "color" -> "green", "sport " -> "网球"})?

我可以通过循环轻松地做到这一点,但有没有更优雅的方法,也许使用 LINQ?

【问题讨论】:

  • 可能是 this question 的副本。至少,解决方案可能几乎相同。
  • 我修正了你的语法;它之前没有编译。
  • 另一个related question 可以帮助你。自身包含指向其他被标记为重复的有用问题的链接。
  • 感谢所有为类似问题提供答案和链接的人。这里有一些有趣且发人深省的想法。我最喜欢的答案是 Turbot 和 digEmAll。

标签: c#


【解决方案1】:
a.Select((input, index) = >new {index})
  .Where(x=>x.index%2!=0)
  .ToDictionary(x => a[x.index], x => a[x.index+1])

我建议使用 for 循环,但我已按照您的要求回答了。这绝不是更整洁/更干净的......

【讨论】:

    【解决方案2】:

    我已经做了一个类似的方法来处理这种类型的请求。但由于您的数组同时包含键和值,我认为您需要先拆分它。

    然后你可以使用这样的东西来组合它们

    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);
        }
    

    【讨论】:

    • 一些建议:名称有误导性,称之为ZipToDictionary(不涉及列表)。并使用描述性类型元素,即TKey, TValue
    • 那么如何从数组中得到两个可枚举?
    • 我刚刚添加了this answer,它使用了这个总体思路,但对其进行了扩展以解决我之前提到的问题。
    【解决方案3】:
    var dict = a.Select((s, i) => new { s, i })
                .GroupBy(x => x.i / 2)
                .ToDictionary(g => g.First().s, g => g.Last().s);
    

    【讨论】:

      【解决方案4】:

      因为它是一个数组,所以我会这样做:

      var result = Enumerable.Range(0,a.Length/2)
                             .ToDictionary(x => a[2 * x], x => a[2 * x + 1]);
      

      【讨论】:

        【解决方案5】:

        这个怎么样?

            var q = a.Zip(a.Skip(1), (Key, Value) => new { Key, Value })
                     .Where((pair,index) => index % 2 == 0)
                     .ToDictionary(pair => pair.Key, pair => pair.Value);
        

        【讨论】:

        • 这是两次遍历列表。这对 IEnumerable 来说也是个问题(我知道问题是关于数组的),它正在做额外的工作。
        【解决方案6】:
        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);
        }
        

        这是设置的方式,并且由于Zip 的工作方式,如果列表中有奇数个项目,则最后一个项目将被忽略,而不是生成某种异常。

        注意:源自this answer.

        【讨论】:

          【解决方案7】:
          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)]);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-09-16
            • 2014-09-02
            • 2010-12-10
            • 1970-01-01
            • 2015-02-11
            • 1970-01-01
            相关资源
            最近更新 更多