将C#字符串数组转换为字典

3

有没有一种优雅的方法将这个字符串数组转换为:

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

把数组转换成一个字典,使得数组中的每两个连续元素成为字典中的一对{key, value}(例如 {"name" -> "Fred", "colour" -> "green", "sport" -> "tennis"})。 我可以通过循环轻松完成它,但是否有更优雅的方式,也许使用LINQ?

可能是这个问题的重复。至少,解决方案可能基本相同。 - O. R. Mapper
我修复了你的语法;之前它没有编译。 - Adam
另一个相关问题可能会对您有帮助。它本身包含其他有用的问题链接,被标记为重复。 - O. R. Mapper
感谢所有为问题提供答案和类似问题链接的人。这里有一些有趣且发人深省的想法。我最喜欢的答案是Turbot和digEmAll提供的。 - Klitos Kyriacou
7个回答

5
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]);

2
这个怎么样?
    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);

1
这会导致列表被遍历两次。对于IEnumerable来说这可能是个问题(我知道问题是关于数组的),而且还会做额外的工作。 - Jeff Walker Code Ranger

1

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

然后,您可以使用类似以下的内容来将它们组合起来

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”。 - Adam
1
那么,你如何从数组转换为两个可枚举对象? - Servy
我刚刚添加了这个答案,它使用了这个通用的想法,但是扩展了它以解决我之前提到的问题。 - Servy

0
a.Select((input, index) = >new {index})
  .Where(x=>x.index%2!=0)
  .ToDictionary(x => a[x.index], x => a[x.index+1])

我建议使用for循环,但我已按照您的要求进行了回答。这绝不是更整洁/更清洁的方法。


0
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.


0
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)]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接