Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cant convert list<object[]> to list <T[]> in C#

I have the following final code:

SqlDataReader dataReader;
dataReader = cmd.ExecuteReader();
// var list = new List<string[]>();
List<T[]> list = new List<T[]>();

while (dataReader.Read())
{
   // var row = new string[dataReader.FieldCount];
    //object[] row new object;
    T[] bass;
    object[] row = new object[dataReader.FieldCount];
    dataReader.GetValues(row);
    bass = (T[]) Convert.ChangeType(row,typeof(T[]));
    list.Add(bass);
}

I kept tried to convert an object array to a T generic type array in different ways, but i didn't make it. For the earlier code i get a runtime error: object must implement IConvertible. I put a constraint for the generic type when i defined the class:

class Cclass<T>: Iinterface<T> where T:IConvertible
{  
    //body 
}

I'm open to other suggestions that can fulfill my goal of casting to generic array. Thank you!

like image 483
postos Avatar asked Mar 18 '23 04:03

postos


1 Answers

You can use Linq:

  bass = row
    .Select(x => (T)Convert.ChangeType(x, typeof(T)))
    .ToArray();
like image 160
Dmitry Bychenko Avatar answered Apr 08 '23 23:04

Dmitry Bychenko