2010-02-18 8 views
20

¿Qué podría ser un LINQ equivalente al siguiente código?Cómo concatenar dos colecciones por índice en 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]); 
} 

Respuesta

24

.NET 4 tiene un operador postal que le permite unir dos colecciones al mismo tiempo.

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

El método .zip es superior a .Elija ((s, i) => ...) porque .Elija será una excepción cuando sus colecciones no tienen el mismo número de elementos, mientras que. Zip simplemente unirá todos los elementos que pueda.

Si tiene .NET 3.5, tendrá que conformarse con. Seleccione o escriba su propio método .Zip.

Ahora, dicho todo esto, nunca he usado Convert.ChangeType. Supongo que funciona para su escenario, así que lo dejo.

+1

O simplemente: 'objetos var = values.zip (tipos, (v, t) => Convert.ChangeType (v, t));' – Ken

+1

Ken, tienes razón. Actualizaré mi publicación. Gracias. –

+0

Actualizado. Gracias por el consejo. –

6

Suponiendo que ambos conjuntos tienen el mismo tamaño:

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(); 
4
object[] objects = values.Select((s,i) => Convert.ChangeType(s, types[i])) 
         .ToArray(); 
Cuestiones relacionadas