简化if语句

时间:2012-12-27 11:14:25

标签: c# .net linq if-statement

我如何简化这样的陈述:

    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)

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:3)

也许这个?

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

PLB REQUEST编辑:)

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

答案 2 :(得分:0)

您可以添加:

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

那是:

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