代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

实体框架4和Linq:OrderBy嵌套在查询中的字段:重构我的代码

  •  2
  • Zachary Scott  · 技术社区  · 15 年前

    第一, Thomas Levesque 有一个很好的解决方案,可以对相关表中的字段进行排序,其中关系可能并不总是存在:

    userQuery = userQuery.OrderBy(u => 
        (u.Department != null) ? u.Department.Name : String.Empty);
    

    我也要这么做。我的总根是巨大的:

    myQuery = myQuery.OrderBy(p =>
      (p.Seconds == null
        ? 0
        : p.Seconds.FirstOrDefault() == null
          ? 0
          : p.Seconds.First().Thirds == null
            ? 0
            : p.Seconds.First().Thirds.FirstOrDefault() == null
              ? 0
              : p.Seconds.First().Thirds.First().Forths == null
                ? 0
                : p.Seconds.First().Thirds.First().Forths.FirstOrDefault() == null
                  ? 0
                  : p.Seconds.First().Thirds.First().Forths.First().myField));
    

    myQuery = myQuery.OrderBy(p =>
      (p.Seconds == null
        ? p.myDefaultField // Used to be zero
        : p.Seconds.FirstOrDefault() == null
          ? p.myDefaultField
          : p.Seconds.First().Thirds == null
            ? p.myDefaultField
            : p.Seconds.First().Thirds.FirstOrDefault() == null
              ? p.myDefaultField
              : p.Seconds.First().Thirds.First().Forths == null
                ? p.myDefaultField
                : p.Seconds.First().Thirds.First().Forths.FirstOrDefault() == null
                  ? p.myDefaultField
                  : p.Seconds.First().Thirds.First().Forths.First().myField));
    

    我怎样才能把这个OrderBy重写得更干净呢?

    1 回复  |  直到 8 年前
        1
  •  2
  •   JAB    15 年前

    我认为您在这里有一种非常难闻的代码味道,但是使用您的代码,我不会在这样的LINQ查询中处理这个问题。只是为了可读性,我会做一些

    myQuery = myQuery.OrderBy(p =>
      (p.HasValidFields()
        ? p.Seconds.First().Thirds.First().Forths.First().myField
        : p.myDefaultField
      ));
    

    private bool HasValidFields
    {
      get
      {
        return p.Seconds != null &&
               p.Seconds.FirstOrDefault() != null &&
               .... ;
      }
    }
    
    推荐文章