在LINQ查询中,我是否可以或应该将两个Where子句连接起来?[英] Can or should I join two Where clauses together in a LINQ Query?

本文是小编为大家收集整理的关于在LINQ查询中,我是否可以或应该将两个Where子句连接起来?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有以下课程:

public partial class Content
{
    public int ContentId { get; set; }
    public int ContentTypeId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }

    public int SubjectId { get; set; }
    public virtual Subject Subject { get; set; }
}

我知道我可以使用这样的 Linq 查询:

.Where(a => a.SubjectId == subjectId)

但是我怎样才能使它有另一个条件

.Where(a => a.ContentTypeId == contentTypId) 

有没有一种方法可以将它们合并为一个,或者它们应该保持为两个?

推荐答案

只使用一个包含所有条件的 Where 子句:

.Where(a => a.SubjectId == subjectId && a.ContentTypeId == contentTypId)

或两个 Where 子句,每个处理一个条件:

.Where(a => a.SubjectId == subjectId)
.Where(a => a.ContentTypeId == contentTypId)

是等价的,因为 LINQ 查询执行被推迟到结果调用.

本文地址:https://www.itbaoku.cn/post/1557060.html

问题描述

I have the following class:

public partial class Content
{
    public int ContentId { get; set; }
    public int ContentTypeId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }

    public int SubjectId { get; set; }
    public virtual Subject Subject { get; set; }
}

I understand I can use a Linq query like this:

.Where(a => a.SubjectId == subjectId)

However how can I make it so there is another condition

.Where(a => a.ContentTypeId == contentTypId) 

is there a way I can join these into one where or should they remain as two?

推荐答案

Using only one Where clause containing every condition:

.Where(a => a.SubjectId == subjectId && a.ContentTypeId == contentTypId)

Or two Where clauses, dealing with one condition each:

.Where(a => a.SubjectId == subjectId)
.Where(a => a.ContentTypeId == contentTypId)

is equivalent, as the LINQ query execution is deferred until the call to the result.