Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 783
user161433 Avatar asked Sep 18 '09 08:09

user161433


People also ask

Can we use if condition in Linq?

Yes you can like: var query = someList. Where(a => a == "something"); if (condition) { query = query. Where(b => b == "something else"); } var result = query.

Which clause is used for conditions in Linq?

In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.

What is Dynamic Linq?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.


1 Answers

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);
like image 134
Jon Skeet Avatar answered Sep 24 '22 00:09

Jon Skeet