我一直试图为我想写的linq查询找到合适的解决方案。
在我的模型结构中,我有我的Item类,它包含一个PaymentRecords列表。我希望我的查询实现的是:
public class PaymentRecord
{
public int PaymentRecordId { get; set; }
[Required]
public double PaymentAmount { get; set; }
[Required]
public DateTime DateOfPayment { get; set; }
[Required]
public bool FinalPayment { get; set; }
[JsonIgnore]
public Item Item{ get; set; }
}
public class Item
{
public int ItemId { get; set; }
public List<PaymentRecord> PaymentRecords {get; set;}
...various other properties
}
选择所有项目,其中PaymentRecord列表与下面的条件匹配(工作正常),或者PaymentRecord为空的地方,例如Items类没有PaymentRecord。有没有办法做到这一点?
var result = m_context.Item
.SelectMany(
x => x.PaymentRecords.Where(p => (p.FinalPayment == true
&& p.DateOfPayment >= _revenueStatementRequest.StartDate
&& p.DateOfPayment <= _revenueStatementRequest.EndDate)
|| p.FinalPayment != true),
(x, p) => x
)
.ToList();
理想情况下,我想做类似下面的事情,但我无法获得类似的工作:
var result = m_context.Item
.SelectMany(
x => x.PaymentRecords.Where(p => (p.FinalPayment == true
&& p.DateOfPayment >= _revenueStatementRequest.StartDate
&& p.DateOfPayment <= _revenueStatementRequest.EndDate)
|| p.FinalPayment != true)
|| x.PaymentRecords == null,
(x, p) => x
)
.ToList();
根据给出的答案,我得到了这个:
m_context.Item.Where(c => (!
c.PaymentRecords.Any(q => (q.FinalPayment &&
q.DateOfPayment >= _revenueStatementRequest.StartDate &&
q.DateOfPayment <= _revenueStatementRequest.EndDate)
|| q.FinalPayment != true
)
)
&& (c..Type == Booked || c.Type == Reserved)
&& (c.StartDate < _revenueStatementRequest.StartDate)
)
答案 0 :(得分:1)
您可以在没有SelectMany
List<Item> res = m_context.Items
.Where(c => !c.PaymentRecords
.Any(q => (q.FinalPayment &&
q.DateOfPayment >=_revenueStatementRequest.StartDate &&
q.DateOfPayment <= _revenueStatementRequest.EndDate)
|| !q.FinalPayment)
)
//**EDIT**
.Where(c => c.StartDate < _revenueStatementRequest.StartDate)
//this is comment out, so we can better test on the more complex part of the query
//.Where(c => c.Type == Booked || c.Type == Reserved)
.ToList();
通过这种方式,您可以获得List<Item>
而不是List<PaymentRecord>
答案 1 :(得分:1)
选择所有项目,其中PaymentRecord列表与条件匹配 下面(工作正常),或者PaymentRecord为空的地方,例如该 Items类没有PaymentRecord。
var result = m_context.Item
.Where(x => !x.PaymentRecords.Any() ||
x.PaymentRecords.Any(p => (p.FinalPayment == true
&& p.DateOfPayment >= _revenueStatementRequest.StartDate
&& p.DateOfPayment <= _revenueStatementRequest.EndDate)
|| p.FinalPayment != true))
.ToList();
我认为在这里使用SelectMany
没有任何理由。简单的Where
条件可以完成工作。