问题描述
我有以下课程:
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 查询执行被推迟到结果调用.
问题描述
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.