User1551892
User1551892

Reputation: 3384

How to cast the List<object> to List<T>?

I am struggling to fix the following problem:

I have list of object and object type is int:

int a = 1;
  int b = 2;
  int c = 3;
  List<object> kk = new List<object>( );
  kk.Add( ( object )a );
  kk.Add( ( object )b );
  kk.Add( ( object )c );

and I want to cast the List<object> to List<objecttype> and in above example object type is int. I want to cast List<object> to List<int>. Is there a way address this problem?

I am looking for generic solution and assume no knowledge of casting type.

enter image description here

Upvotes: 6

Views: 22325

Answers (5)

User1551892
User1551892

Reputation: 3384

   var typeofkk = kk.ToArray( ).Select( x => x.GetType( ) ).ToArray( ).FirstOrDefault( );
   Array ll = Array.CreateInstance( typeofkk, kk.Count );
   Array.Copy( kk.ToArray (), ll, kk.Count );

perhaps, this is not the solution which I was looking for but somehow it solved my problem.

Upvotes: 1

mhafellner
mhafellner

Reputation: 468

Maybe you could try something like this:

List<object> objects = new List<object>();
List<int> ints = objects.Select(s => (int)s).ToList();

Should work for all types.

So in general:

List<object> objects = new List<object>();
List<objecttype> castedList = objects.Select(s => (objecttype)s).ToList();

Upvotes: 6

ducmami
ducmami

Reputation: 215

Try this:

var newList = kk.Cast<int>().ToList();

Upvotes: 1

Ash Clarke
Ash Clarke

Reputation: 4887

Try using .Cast<int>() on your list, kk.

Upvotes: 0

Aron
Aron

Reputation: 15772

Two ways to do it with linq

This version will throw if any of the objects aren't int.

var ints = kk.Cast<int>().ToList();

This version will leave you only the ones that CAN be cast to int.

var ints = kk.OfType<int>().ToList();

Upvotes: 20

Related Questions