说我有一个User
数组:
class User : IUserDowngraded
{
public Int32 Id { get; set; }
}
...通过将对象强制转换为特定接口来完成降级功能:
interface IUserDowngraded
{
Int32 Id { get; } // removes set functionality from property
}
...如何使用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++;
}
答案 0 :(得分:2)
var upgradedUsers = downgradedUsers.Cast<User>();
如果您希望将ToArray()
作为数组,请附加对upgradedUsers
的调用。
答案 1 :(得分:0)
SampleIntList = SampleStringList.Cast<int>().Select(x => Convert.ToInt32(x)).ToList();
答案 2 :(得分:0)