Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 666
User1551892 Avatar asked May 24 '13 09:05

User1551892


2 Answers

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();
like image 165
Aron Avatar answered Oct 03 '22 03:10

Aron


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();
like image 32
mhafellner Avatar answered Oct 03 '22 03:10

mhafellner