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?
You should be able to do this with just one mapping1:
You need to map a KeyValuePair<User, bool>
to UserDto
. This is necessary for AutoMapper to be able to map the contents of the dictionary to the contents of the List<T>
we're ultimately creating (more of an explanation can be found in this answer).
Mapper.CreateMap<KeyValuePair<User, bool>, UserDto>()
.ForMember(dest => dest.Username, opt => opt.MapFrom(src => src.Key.UserName))
.ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.Key.Avatar))
.ForMember(dest => dest.IsFriend, opt => opt.MapFrom(src => src.Value));
Then, use the mapping in your .Map
call:
Mapper.Map<Dictionary<User, bool>, List<UserDto>>(...);
You don't need to map the collections themselves, as AutoMapper can handle mapping the Dictionary
to a List
as long as you've mapped the contents of the collections to each other (in our case, KeyValuePair<User, bool>
to UserDto
).
Edit: Here's another solution that doesn't require mapping every User
property to UserDto
:
Mapper.CreateMap<User, UserDto>();
Mapper.CreateMap<KeyValuePair<User, bool>, UserDto>()
.ConstructUsing(src => Mapper.Map<User, UserDto>(src.Key))
.ForMember(dest => dest.IsFriend, opt => opt.MapFrom(src => src.Value));
1Using AutoMapper 2.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With