Linq If Statement

时间:2009-09-18 08:06:30

标签: linq linq-to-entities

我如何在linq中将这样的内容写入实体

sb.Append(" WHERE question.question_isdeleted = 0");
    if (catid != 0)
        sb.AppendFormat(" AND (CatID IN ({0}))", catsSTR);
    if(!string.IsNullOrEmpty(AuthorID))
        sb.Append(" AND (question_ownerid = @id)");

我想我只需要语法就可以在linq中编写if条件到实体

3 个答案:

答案 0 :(得分:14)

我会在这里使用点符号:

var query = questions.Where(q => !q.IsDeleted);

if (catId != 0)
{
    query = query.Where(q => cats.Contains(q.CatID));
}
if (authorId != 0)
{
    query = query.Where(q => q.OwnerId == authorId);
}

您可以编写自己的扩展方法,以便更简单地执行此操作:

public static IQueryable<T> OptionalWhere<T>(
    this IQueryable<T> source,
    bool condition, 
    Expression<Func<T,bool>> predicate)
{
    return condition ? source.Where(predicate) : source;
}

然后你可以写:

var query = questions.Where(q => !q.IsDeleted);
                     .OptionalWhere(catId != 0, q => cats.Contains(q.CatID))
                     .OptionalWhere(authorId != 0, q => q.OwnerId == authorId);

答案 1 :(得分:0)

您可以有条件地构建如下查询:

 var query = from q in questions
             where q.question_isdeleted
             select q;
 if(!string.IsNullOrEmpty(AuthorID))
 {
     query = from q in query
             where q.question_ownerid == AuthorID
             select q;
 }

但是,LINQ to Entities没有类似SQL IN运算符的好构造......

答案 2 :(得分:-1)

where question.question_isdeleted = 0
  && (catid != 0 
     ? catsStr.Contains(CatId.ToString())
     : question_ownerId == id)

不确定字符串操作是否正确,但逻辑看起来是正确的。