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

时间:2009-05-06 00:44:31

标签: c# linq

说我有一个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++;
}

3 个答案:

答案 0 :(得分:2)

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

如果您希望将ToArray()作为数组,请附加对upgradedUsers的调用。

答案 1 :(得分:0)

use the cast method....

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

答案 2 :(得分:0)