I have two objects.
class User{
public int id{get;set;}
public string name{get;set;}
}
class UserProtectedDetails{
public string name{get;set;}
}
How can I convert List<User>
to List<UserProtectedDetails>
?
I know how to do it in reflection, but is there anyway to do it in Linq or other .NET way?
is there anyway to do it in linq or other .net way?
Sure:
List<User> list = ...; // Make your user list
List< UserProtectedDetails> = list
.Select(u => new UserProtectedDetails{name=u.name})
.ToList();
EDIT: (in response to a comment) If you would like to avoid the {name = u.name}
part, you need either (1) a function that makes a mapping for you, or (2) a constructor of UserProtectedDetails
that takes a User
parameter:
UserProtectedDetails(User u) {
name = u.name;
}
One way or the other, the name = u.name
assignment needs to be made somewhere.