Linq If Statement

只谈情不闲聊 提交于 2019-12-18 10:57:12

问题


How would i write something like this in linq to entities

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)");

i think I just need the syntax to write an if conditional in linq to entities


回答1:


I would use dot notation here:

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);
}

You could write your own extension method to do this slightly more simply:

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

You could then write:

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



回答2:


You can conditionally build a query like this:

 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;
 }

However, LINQ to Entities have no good construct that resembles the SQL IN operator...




回答3:


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

Not sure if the string operations are correct, but the logic looks correct.



来源:https://stackoverflow.com/questions/1443152/linq-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!