如何通过LINQ指数加入两个集合 [英] How to join two collections by index in LINQ
问题描述
什么可能是一个LINQ相当于下面的代码?
的String []值= {1,你好,真};
类型[]类型= {typeof运算(INT),typeof运算(字符串),typeof运算(布尔)};
对象[]对象=新的对象[values.Length]
的for(int i = 0; I< values.Length;我++)
{
对象由[i] = Convert.ChangeType(值[I],类型[我]);
}
.NET 4有一个Zip 。运营商可以让你加入两个集合在一起
VAR值= {1,你好,真};
变种类型= {typeof运算(INT),typeof运算(字符串),typeof运算(布尔)};
无功对象= values.Zip(类型,(VAL,类型)=> Convert.ChangeType(VAL,类型));
的.zip方法优于。选择((S,I)=> ...)因为。选择将抛出一个异常时,你的藏品不具有相同数量的元素,而.ZIP将简单地压缩在一起一样多的元素就可以了。
如果你在.NET 3.5,那么你不得不接受。选择,或者自己写的.zip方法。
现在,所有的说,我从未使用过Convert.ChangeType。我假设它适用于您的情况,所以我会离开,是。
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 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));
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.
If you're on .NET 3.5, then you'll have to settle for .Select, or write your own .Zip method.
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屋!