如何在LINQ中按索引连接两个集合 [英] How to concatenate two collections by index in LINQ

查看:153
本文介绍了如何在LINQ中按索引连接两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与下面的代码等效的LINQ是什么?

What could be a LINQ equivalent to the following code?

string[] values = { "1", "hello", "true" };
Type[] types = { typeof(int), typeof(string), typeof(bool) };

object[] objects = new object[values.Length];

for (int i = 0; i < values.Length; i++)
{
    objects[i] = Convert.ChangeType(values[i], types[i]);
}

推荐答案

.NET 4具有一个Zip运算符,可让您将两个集合连接在一起.

.NET 4 has a Zip operator that lets you join two collections together.

var values = { "1", "hello", "true" };
var types = { typeof(int), typeof(string), typeof(bool) };
var objects = values.Zip(types, (val, type) => Convert.ChangeType(val, type));

.Zip方法优于.Select((s,i)=> ...),因为当您的集合没有相同数量的元素时.Select将引发异常,而.Zip只会压缩尽可能多地结合在一起.

The .Zip method is superior to .Select((s, i) => ...) because .Select will throw an exception when your collections don't have the same number of elements, whereas .Zip will simply zip together as many elements as it can.

如果使用的是.NET 3.5,则必须满足.Select或编写自己的.Zip方法.

If you're on .NET 3.5, then you'll have to settle for .Select, or write your own .Zip method.

现在,所有这些,我从未使用过Convert.ChangeType.我假设它适用于您的情况,所以我将其保留.

Now, all that said, I've never used Convert.ChangeType. I'm assuming it works for your scenario, so I'll leave that be.

这篇关于如何在LINQ中按索引连接两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆