0

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++;
}
cllpse
  • 21,396
  • 37
  • 131
  • 170

3 Answers3

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

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

Noldorin
  • 144,213
  • 56
  • 264
  • 302
0

use the cast method....

SampleIntList = SampleStringList.Cast<int>().Select(x => Convert.ToInt32(x)).ToList();
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
0

Also any of Implicit operators, Linq and Lambda expressions can make code less readable. But what is more readable? methods should work.

Community
  • 1
  • 1
David McEwing
  • 3,320
  • 18
  • 16