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++;
}

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

use the cast method....

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.