我知道我們可以使用.ToDictionary(t => t.Key,t => t.Value)將linq結果集轉換爲Dictionary集合,但我正在尋找更多的東西。我想給LINQ結果轉換爲IEnumerable<Dictionary<string, object>>
和下面是我在尋找:將Linq結果轉換爲字典的最佳實踐
這裏是我的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應用程序。
感謝, Binoy
很好,它絕對有助於改善代碼,感謝您的幫助,不能將此標記爲低點答案。 – Binoy
不幸的是TypeDescriptor在WP8中不可用 – Binoy
我檢查了RouteValueDictionary的代碼,它在AddValues方法中使用TypeDescriptor,我試圖以相同的方式更新代碼,但發現WP8中不存在TypeDescriptor – Binoy