使用LINQ在一行代码中对数组中的每个对象进行类型转换

时间:2022-04-20 19:39:01

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:

...如何使用LINQ将这些降级的对象(IUserDowngraded)转换为单行代码中的User对象?我想避免的是:

// 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 个解决方案

#1


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

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

当然,如果你想将升级的用户作为数组,请附加对ToArray()的调用。

#2


use the cast method....

使用演员方法....

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

#3


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

任何Implicit运算符,Linq和Lambda表达式都会使代码的可读性降低。但更具可读性的是什么?方法应该有效。

#1


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

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

当然,如果你想将升级的用户作为数组,请附加对ToArray()的调用。

#2


use the cast method....

使用演员方法....

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

#3


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

任何Implicit运算符,Linq和Lambda表达式都会使代码的可读性降低。但更具可读性的是什么?方法应该有效。