在 C# 中将两个列表映射到字典中

2024-04-14

给定两个 IEnumerables 同样大小,如何转换为 Dictionary 使用林克?

IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };

var dictionary = /* Linq ? */;

预期输出是:

A: Val A
B: Val B
C: Val C

我想知道是否有一些简单的方法可以实现它。

我应该担心性能吗?如果我有大量收藏怎么办?


我不知道是否有更简单的方法来做到这一点,目前我正在这样做:

我有一个扩展方法,它将循环IEnumerable为我提供元素和索引号。

public static class Ext
{
    public static void Each<T>(this IEnumerable els, Action<T, int> a)
    {
        int i = 0;
        foreach (T e in els)
        {
            a(e, i++);
        }
    }
}

我有一种方法可以循环其中一个枚举,并使用索引检索另一个枚举上的等效元素。

public static Dictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<TKey> keys, IEnumerable<TValue> values)
{
    var dic = new Dictionary<TKey, TValue>();

    keys.Each<TKey>((x, i) =>
    {
        dic.Add(x, values.ElementAt(i));
    });

    return dic;
}

然后我像这样使用它:

IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };

var dic = Util.Merge(keys, values);

并且输出是正确的:

A: Val A
B: Val B
C: Val C

使用 .NET 4.0(或来自 Rx 的 System.Interactive 3.5 版本),您可以使用Zip():

var dic = keys.Zip(values, (k, v) => new { k, v })
              .ToDictionary(x => x.k, x => x.v);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中将两个列表映射到字典中 的相关文章

随机推荐