I've got a Dictionary<User, bool>
User is as follows:
public class User {
public string Username { get; set; }
public string Avatar { get; set;
}
The second type, bool, indicates whether this user is a friend of the logged in User.
I want to flatten this Dictionary into a List<UserDto
> UserDto is defined as:
public class UserDto {
public string Username { get; set; }
public string Avatar { get; set; }
public bool IsFriend { get; set; }
}
IsFriend
represents the value of the dictionary.
How can I do this?
I know I am late to the game, yet this seems to be a more generic solution for mapping a dictionary to a .Net type(simple) using automapper
Use it like this
where TDestination can a .NET simple type. For complex types, you could supply a Func/Action delegate and map using that function.(Inside the above for-each)
Eg.
You should be able to do this with just one mapping1:
You need to map a
KeyValuePair<User, bool>
toUserDto
. This is necessary for AutoMapper to be able to map the contents of the dictionary to the contents of theList<T>
we're ultimately creating (more of an explanation can be found in this answer).Then, use the mapping in your
.Map
call:You don't need to map the collections themselves, as AutoMapper can handle mapping the
Dictionary
to aList
as long as you've mapped the contents of the collections to each other (in our case,KeyValuePair<User, bool>
toUserDto
).Edit: Here's another solution that doesn't require mapping every
User
property toUserDto
:1Using AutoMapper 2.0
For something simple like this, a quick LINQ query will do. Assuming
dict
is yourDictionary<User,bool>
: