0

我怎样才能简化这样的陈述:

    var someList = new List<someType>();

    if (String.IsNullOrEmpty(groupId))
    {
        someList = CTX.Values.Include(c => c.Customer).ToList();
    }
    else
    {
        someList = CTX.Values.Include(c => c.Customer).Where(c => c.GroupId== groupId).ToList();

    }

区别仅在.Where(c => c.GroupId== groupId). 是否可以String.IsNullOrEmpty(groupId)在查询语句中包含条件?

4

3 回答 3

7

您可以分多个步骤构建查询。仅在不为空时才添加该Where部分。groupId

查询只会在您调用ToList().

var values = CTX.Values.Include(c => c.Customer);

if(!String.IsNullOrEmpty(groupId))
  values = values.Where(c => c.GroupId == groupId);

someList = values.ToList();
于 2012-12-27T11:18:05.023 回答
3

也许这个?

someList = CTX.Values.Include(c => c.Customer)
       .Where(c => String.IsNullOrEmpty(groupId)
                   || c.GroupId== groupId)
       .ToList();

由 PLB 请求编辑 :)

bool isGroupValid = String.IsNullOrEmpty(groupId);
someList = CTX.Values.Include(c => c.Customer)
       .Where(c => isGroupValid
               || c.GroupId== groupId)
       .ToList();
于 2012-12-27T11:17:26.843 回答
0

你可以加:

.Where(c => String.IsNullOrEmpty(groupId))

那是:

CTX.Values.Include(c => c.Customer)
    .Where(c => c.GroupId == groupId || c => String.IsNullOrEmpty(groupId))
    .ToList();
于 2012-12-27T11:18:55.067 回答