LINQ IQueryable查询

时间:2013-09-30 07:52:24

标签: c# linq

这是我从数据库中检索非活动/活动用户列表的查询。我的问题是,我的查询似乎太复杂了。那么请你给我一个如何增强查询的提示。

这是我的代码

            using (basecampcoreEntities dbs = ConfigAndResource.BaseCampContext())
        {
            //loads all user where isactive property has the same value as IsActive
            var Users = from useritem in dbs.users
                        where useritem.useraccount.IsActive.Equals(IsActive)
                        orderby useritem.useraccount.CreatedDate
                        select useritem;

            //check if users count is greater than 0
            if (Users.Count() > 0)
            {

                List<user> CasebookUser = new List<user>();
                switch (SearchBy)
                {
                    case DTO::SearchBy.FirstName:
                        {
                            CasebookUser = Users.Where(item => item.FirstName.ToUpper().Equals(SearchText.ToUpper())).Skip(skip).Take(take).ToList();
                        } break;
                    case DTO::SearchBy.LastName:
                        {
                            CasebookUser = Users.Where(item => item.LastName.ToUpper().Equals(SearchText.ToUpper())).Skip(skip).Take(take).ToList();
                        } break;
                    case DTO::SearchBy.LoginID:
                        {
                            CasebookUser = Users.Where(item => item.LoginID.ToUpper().Equals(SearchText.ToUpper())).Skip(skip).Take(take).ToList();
                        } break;
                    case DTO::SearchBy.None:
                            CasebookUser = Users.Skip(skip).Take(take).ToList();
                        {
                        } break;
                }

                //transform the data into DTO class
                return (from item in CasebookUser
                        select new DTO::User
                        {
                            LoginID = item.LoginID,
                            FirstName = item.FirstName,
                            LastName = item.LastName,
                            MiddleName = item.MiddleName,
                            Birhtday = item.userinfo != null ? item.userinfo.Birthday : DateTime.UtcNow
                        }).ToList();
            }
            return null;

2 个答案:

答案 0 :(得分:2)

利用延迟执行的力量......

// first filter by whether user is active or not
var query = dbs.users.Where(x => x.useraccount.IsActive == IsActive);    

// next filter by specific search field
switch (SearchBy)
{
    case DTO::SearchBy.FirstName:
    {
        query = query.Where(x => string.Equals(x.FirstName, SearchText, StringComparison.InvariantCultureIgnoreCase)); 
        break;
    }
    case DTO::SearchBy.LastName:
    {
        query = Users.Where(x => string.Equals(x.LastName, SearchText, StringComparison.InvariantCultureIgnoreCase));
        break;
    }
    ...
}

// then apply paging
query = query.Skip(skip).Take(take);

// finally, order by CreatedDate (ascending)
query = query.OrderBy(x => x.useraccount.CreatedDate);

// now fetch the records!
return (from item in query
        select new DTO::User
        {
            LoginID = item.LoginID,
            FirstName = item.FirstName,
            LastName = item.LastName,
            MiddleName = item.MiddleName,
            Birhtday = item.userinfo != null ? item.userinfo.Birthday : DateTime.UtcNow
         }).ToList();

此代码将以更优化的方式为您提供所需的内容(仅1个数据库行程) - 并且它在讨价还价中更具可读性。

答案 1 :(得分:1)

我会:

  1. 从原始查询定义中删除排序
  2. 请勿将ToList()转换为Skip()' and Take()`过早地
  3. 不要施放ToList()两次。只有在创建最终集合时才能这样做。
  4. 在初始查询中更明确地进行IsActive比较
  5. 将第一个查询重写为一行linq表达式
  6. 使用Any()代替Count() > 0
  7. 只转换一次您的搜索文本ToUpper()。使您的搜索案例更简洁,更易读(与使用==而非Equals
  8. 相同

    此代码可能有所帮助:

    using (basecampcoreEntities dbs = ConfigAndResource.BaseCampContext())
    {
      //loads all user where isactive property has the same value as IsActive
      var Users = db.Users.Where(x => x.useraccount.IsActive == IsActive);
    
      if (Users.Any())
      {
        var searchText = SearchText.ToUpper();
        switch (SearchBy)
        {
          case DTO::SearchBy.FirstName:
            Users = Users.Where(item => item.FirstName.ToUpper() == searchText);
            break;
          case DTO::SearchBy.LastName:
            Users = Users.Where(item => item.LastName.ToUpper() == searchText);
            break;
          case DTO::SearchBy.LoginID:
            Users = Users.Where(item => item.LoginID.ToUpper() == searchText);
            break;
       }
    
       // apply sort and skip/take
       Users = Users.OrderBy(x => x.useraccount.CreateDate).Skip(skip).Take(take);
    
       //transform the data into DTO class
       return (from item in Users 
               select new DTO::User
               {
                  LoginID = item.LoginID,
                  FirstName = item.FirstName,
                  LastName = item.LastName,
                  MiddleName = item.MiddleName,
                  Birthday = item.userinfo != null ? item.userinfo.Birthday : DateTime.UtcNow
               }).ToList();
        }
        return null;
    }