Typecast each object in an array in one line of code using LINQ

Let's say I have an array User

:

class User : IUserDowngraded
{
    public Int32 Id { get; set; }
}

      

... with reduced functionality done by casting objects into a specific interface:

interface IUserDowngraded
{
    Int32 Id { get; } // removes set functionality from property
}

      

... how would I transfer these downgraded ( IUserDowngraded

) objects User

to objects in one line of code using LINQ?



I am trying to avoid this:

// pseudo-code alert:
IUserDowngraded[] downgradedUsers { IUserDowngraded, IUserDowngraded, ... };

var upgradedUsers = new User[downgradedUsers.Count()];

Int32 i = 0;

foreach (IUserDowngraded du in downgradedUsers)
{
    upgradedUsers[i] = (User)user;

    i++;
}

      

0


a source to share


3 answers


var upgradedUsers = downgradedUsers.Cast<User>();

      



Add call ToArray()

if you want upgradedUsers

as an array, of course.

+2


a source


use the casting method ....



SampleIntList = SampleStringList.Cast<int>().Select(x => Convert.ToInt32(x)).ToList();

      

0


a source


0


a source







All Articles