-
-
Save NinoFloris/4d7e41975fc9f07c3906 to your computer and use it in GitHub Desktop.
Map scalar values from Dapper rows to dto objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class IEnumerableExtension { | |
public static IEnumerable<TFirst> Map<TFirst, TSecond, TKey> | |
( | |
this IEnumerable<TFirst> firstList, | |
Func<TFirst, TKey> firstKey, | |
Func<TSecond, TKey> secondKey, | |
Action<TFirst, IEnumerable<TSecond>> addChildren, | |
Func<IEnumerable<TSecond>> secondList | |
) | |
{ | |
var first = firstList.ToList(); | |
var childMap = secondList() | |
.GroupBy(s => secondKey(s)) | |
.ToDictionary(g => g.Key, g => g.AsEnumerable()); | |
foreach (var item in first) | |
{ | |
IEnumerable<TSecond> children; | |
if(childMap.TryGetValue(firstKey(item), out children)) | |
{ | |
addChildren(item,children); | |
} | |
} | |
return first; | |
} | |
} | |
var data = reader.Read<object>(); | |
collection.Map<DTO, object, int>( | |
dto => dto.id, | |
dict => Convert.ToInt32(((IDictionary<string, object>)dict)["seconddtoid"]), | |
(dto, dict) => { | |
dto.prop = Convert.ToInt32(((IDictionary<string, object>)(dict.First()))["likecount"]); | |
}, | |
() => { | |
return data; | |
} | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment