Linq If语句 [英] Linq If Statement

查看:63
本文介绍了Linq If语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我认为我只需要语法即可将linq中的if条件写给实体

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

推荐答案

我将在此处使用点符号:

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

您可以这样写:

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

这篇关于Linq If语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆