SexyMF
SexyMF

Reputation: 11185

How to convert list of objects from one type to an other

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?

Upvotes: 3

Views: 580

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

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.

Upvotes: 3

Mario S
Mario S

Reputation: 11955

Well, it could be as easy as

var userList = new List<User>();

var userProtectedDetailsList = userList.Select(u => 
    new UserProtectedDetails { name = u.name }
)
.ToList();

Upvotes: 0

Related Questions