如何在LINQ中通过索引连接两个集合

什么可能是LINQ等效于以下代码?

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运算符,允许您将两个集合连接在一起。

 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会在你的集合中没有相同数量的元素时抛出exception,而.Zip会简单地压缩到一起元素尽可能。

如果您使用的是.NET 3.5,那么您将不得不满足于.Select,或编写自己的.Zip方法。

现在,所有这一切,我从未使用过Convert.ChangeType。 我假设它适用于你的场景,所以我会留下它。

假设两个数组具有相同的大小:

 string[] values = { "1", "hello", "true" }; Type[] types = { typeof(int), typeof(string), typeof(bool) }; object[] objects = values .Select((value, index) => Convert.ChangeType(value, types[index])) .ToArray(); 
 object[] objects = values.Select((s,i) => Convert.ChangeType(s, types[i])) .ToArray();