我有两个对象。
class User{
public int id{get;set;}
public string name{get;set;}
}
class UserProtectedDetails{
public string name{get;set;}
}
如何转换 List<User>
至 List<UserProtectedDetails>
?
我知道如何在反射(reflection)中做到这一点,但无论如何都可以用 Linq 或其他 .NET 方式做到这一点吗?
最佳答案
is there anyway to do it in linq or other .net way?
当然:
List<User> list = ...; // Make your user list
List< UserProtectedDetails> = list
.Select(u => new UserProtectedDetails{name=u.name})
.ToList();
编辑:(响应 comment)如果您想避免 {name = u.name}
部分,您需要 (1)为您创建映射的函数,或 (2) UserProtectedDetails
的构造函数,它接受一个 User
参数:
UserProtectedDetails(User u) {
name = u.name;
}
不管怎样,name = u.name
赋值需要在某处进行。
关于.net - 如何将对象列表从一种类型转换为另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018504/