Given two IEnumerables of the same size, how can I convert it to a Dictionary using Linq?

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

var dictionary = /* Linq ? */;

预计yields 为:

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

我有一个方法,它将循环一个Enumerable,并使用索引检索另一个Enumerable上的等价元素.

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

.net相关问答推荐

在接口内部声明 IEnumerable 而在具体类中声明 IList

为什么具有可为空值的 struct 的 HashSet 非常慢?

如何从控制台应用程序中的 Task.WaitAll() 获取返回值?

在一个 LINQ 查询中获取两列的总和

如何在 EF 代码优先中禁用链接表的级联删除?

我可以使用 UriTemplate 将非字符串传递给 WCF RESTful 服务吗?

如何右对齐 DataGridView 列中的文本?

如何在 .NET 中将字符串转换为字节数组?

如何等到远程 .NET 调试器附加

C# 中基于接口编程的运算符重载

.NET 反射的成本是多少?

如何在 RabbitMQ 中设置重试次数?

为什么 C# 不推断我的泛型类型?

如何仅在需要时提升权限?

EF Core 添加迁移构建失败

如何从 WCF REST 方法返回自定义 HTTP 状态代码?

读取 XML(从字符串)并获取一些字段 - 读取 XML 时出现问题

实体框架太慢了.我有哪些 Select ?

在类型 c# 上切换大小写

从 bcp 客户端接收到 colid 6 的无效列长度