【发布时间】:2013-11-28 00:36:40
【问题描述】:
我知道我们可以使用 .ToDictionary(t => t.Key, t => t.Value) 将 linq 结果集转换为 Dictionary 集合,但我正在寻找更多内容。我想将给定的 linq 结果转换为IEnumerable<Dictionary<string, object>>,这就是我要找的:
这是我的 linq 查询:
var query = from v in dbContext.Persons
where !v.InActive
select new
{
v.PersonId,
v.Name,
v.DateOfBirth,
};
this.Persons = query.ToDictionaryCollection();
ToDictionaryCollection 如下所示:
public static IEnumerable<Dictionary<string, object>> ToDictionaryCollection<T>(this IEnumerable<T> collection) where T : class
{
if (collection == null || collection.Count() == 0)
{
return new List<Dictionary<string, object>>();
}
Type givenType = collection.First().GetType();
PropertyInfo[] properties = givenType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
return collection
.Select(entity =>
{
return properties.Select(prop => new { Key = prop.Name, Value = prop.GetValue(entity) }).ToDictionary(prop => prop.Key, prop => prop.Value);
});
}
在当前的实现中,我相信对每个实体使用反射都会受到惩罚。有没有更好的方法,使用 lambda 表达式树或类似的东西?
注意:以上代码适用于 Windows Phone 8 和 Windows Store 8.1 应用程序。
谢谢, 比诺伊
【问题讨论】:
标签: c# linq collections dictionary windows-phone-8