views:

129

answers:

3
+2  Q: 

Linq If Statement

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

A: 
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.

AndreasN
That would cause LINQ to Entities to try and translate the entire statement to SQL, which would not make sense if `catid` is unknown in the database. An additional problem with this answer is that it would add a where clause *either* on `catsStr` *or* `question_ownerId`. That is not what was asked for.
Mark Seemann
Variables in LINQ to Entities become params in SQL, so it's legal to use catId here.
Craig Stuntz
A: 

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...

Mark Seemann
+3  A: 

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);
Jon Skeet
Jon, love the OptionalWhere extension method. Totally awesome :) /me steals that platinum nugget...
Pure.Krome
hey that is some awesome code...nice