postos
postos

Reputation: 41

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!

Upvotes: 4

Views: 1215

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

You can use Linq:

  bass = row
    .Select(x => (T)Convert.ChangeType(x, typeof(T)))
    .ToArray();

Upvotes: 5

David S.
David S.

Reputation: 6105

You can't convert an array of T1 to a collection of T2, even if T1 can be cast to T2. Look up http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx. A simpler solution would be to iterate through each object in the row and cast them individually.

Upvotes: 2

Related Questions