【问题标题】:Best practice for translating Linq result to Dictionary将 Linq 结果翻译成 Dictionary 的最佳实践
【发布时间】: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


    【解决方案1】:

    看起来您正在尝试做一些与RouteValueDictionary 在System.Web 世界中所做的非常相似的事情。您将无法绕过进行反思的需要,但通过查看 their source code,您可能会从微软如何解决此问题中受益。

    如果您创建了一个类似于他们的 Dictionary 类(例如“DynamicDictionary”),那么您可以将方法更改为:

    if (collection == null)
    {
        return new List<Dictionary<string, object>>();
    }
    return collection.Select(e => new DynamicDictionary(e));
    

    当然,我建议让您的方法返回一个 IDictionary(甚至是 IReadOnlyDictionary 接口,这样您就不会与特定的字典实现紧密耦合。

    【讨论】:

    • 太棒了,它确实有助于改进代码,感谢您的帮助,由于分数低,无法将其标记为答案。
    • 很遗憾 TypeDescriptor 在 WP8 中不可用
    • 我检查了 RouteValueDictionary 的代码,它在 AddValues 方法中使用了 TypeDescriptor,我试图以相同的方式更新代码,但发现 WP8 中不存在 TypeDescriptor
    • @user2993678:很不幸。我想您将不得不使用您已经采用的GetProperties 方法。
    【解决方案2】:

    似乎您的代码完全符合您的要求。你可以改变几件小事:

    变化:

    Type givenType = collection.First().GetType();

    到

    Type givenType = typeof(T);

    并且还要改变这个:

    return properties.Select(prop => new { Key = prop.Name, Value = prop.GetValue(entity) }).ToDictionary(prop => prop.Key, prop => prop.Value);
    

    到

    return properties.ToDictionary(prop => prop.Name, prop => prop.GetValue(entity));
    

    如果您尝试获取在类上定义的所有属性并返回其 C# 名称,则无法避免反射。仅获取您知道需要的特定属性的值并在其他地方(例如在视图中)定义名称更有意义。但设计选择取决于您。

    【讨论】:

      【解决方案3】:

      您可以为每个属性创建一个 getter 委托并重用它们,而不是调用 prop.GetValue()。 如果您要迭代的集合足够大,这将很有用。

      var properties = typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .Select(
              p =>
              new
                  {
                      Name = p.Name,
                      Getter = (Func<T, object>) Delegate.CreateDelegate(typeof (Func<T, object>), p.GetGetMethod())
                  })
          .ToList();
      
      return collection.Select(i => properties.ToDictionary(p => p.Name, p => p.Getter(i)));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-29
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 2013-04-22
        • 2014-01-02
        • 1970-01-01
        相关资源
        最近更新 更多