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.
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With