tags:

views:

70

answers:

3

Say I've got an array of User:

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

... with downgraded functionality done by casting the objects to a specific interface:

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

... how would I cast those downgraded objects (IUserDowngraded) to User objects in a single line of code, using LINQ?


What I'm trying to avoid is 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++;
}
+2  A: 
var upgradedUsers = downgradedUsers.Cast<User>();

Append a call to ToArray() if you want upgradedUsers as an array, of course.

Noldorin
Guess I kind'a missed that method. Thanks :)
roosteronacid
Yeah, LINQ has lots of goodies that are easy to miss... This is a particularly useful one. :)
Noldorin
A: 

use the cast method....

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