score:0

ok if you want to avoid forloop and do it with linq is still possible

here is what i gott

var lista = new list<string>();
    lista.add("test");
    lista.add("123");
    lista.add("5.7");

   var listb = new list<type>();
    listb.add(typeof(string));
    listb.add(typeof(int));
    listb.add(typeof(float));
   var index =-1;

try{
var newlist = lista.select((x, i)=>  convert.changetype(x, listb[(index = i)])).tolist();

}catch(exception e){

 throw  new exception("failed to cast value "+lista[index]+" to "+listb[index]);

}

score:1

you could zip the lists together, then use the convert.changetype method

returns an object of a specified type whose value is equivalent to a specified object.

it will throw an exception of the following types

  • invalidcastexception this conversion is not supported. -or- value is null and conversiontype is a value type. -or- value does not implement the iconvertible interface.

  • formatexception value is not in a format recognized by conversiontype.

  • overflowexception value represents a number that is out of the range of conversiontype.

  • argumentnullexception conversiontype is null.

example

var lista = new list<string> { "test", "123", "5.7" };
var listb = new list<type> { typeof(string), typeof(int), typeof(int) };
    
var combined = lista.zip(listb, (s, type) => (value :s, type:type));

foreach (var item in combined)
{
   try
   {
      convert.changetype(item.value, item.type);
   }
   catch (exception ex)
   {
      throw new invalidoperationexception($"failed to cast value {item.value} to {item.type}",ex);
   }
}

full demo here

side note: technically speaking this is not casting per se, it's changing/converting the type

score:1

you could do the following with zip.

var result = lista.zip(listb,(value,type)=> 
                        { 
                           try{return convert.changetype(value,(type)type);} 
                           catch{throw new exception($"cannot cast between value {value} to type {type}");}
                        });

by having the conversion within the zip, would ensure you wouldn't have to convert the whole list if there is an exception earlier in the list.


Related Query

More Query from same tag