Skip to content

Instantly share code, notes, and snippets.

@NinoFloris
Created March 14, 2016 20:58
Show Gist options
  • Save NinoFloris/4d7e41975fc9f07c3906 to your computer and use it in GitHub Desktop.
Save NinoFloris/4d7e41975fc9f07c3906 to your computer and use it in GitHub Desktop.
Map scalar values from Dapper rows to dto objects
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