Posts Tagged - linq

Linq examples

How to map List of classes

// Method to show call usage. 
public List<MappedUser> MapListOfUsers(List<User> users)
{
	// option 1
	List<MappedUser> mappedUsers = users.Select(user => MapSingleUser(user))
		.ToList();
	
	// option 2
	List<MappedUser> mappedUsers2 = 
		(from user in users select MapSingleUser(user)).ToList();
}

method to encapsulate mapping itself

private MappedUser MapSingleUser(User user)
{
 var mapped = new MappedUser
 {
	 Id = user.Id,
	 Name = user.Name,
	 Email = user.Email
 };
 return mapped;
}

This provides easier and more legible than doing a foreach to iterate everything.

Read More