Reputation: 3384
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.
Upvotes: 6
Views: 22325
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
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
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