[英]C# How to use Linq on an XmlAttributeCollection within another Linq statement?
[英]C# LINQ accessing another property within a LINQ SELECT statement (method)
我有一个问题,它涉及是否可以在LINQ中访问另一个属性以便在LINQ中设置另一个属性的值:
var v = ctx.myTableItems
.Where(x => x.id== anotherid)
.Select(e => new MyViewModel
{
Title = e.Title,
CurrentPrice = e.CurrenctPrice.Value,
ItemID = e.ItemID.ToString(),
Transactions= e.Transactions,
Sales =
})
.Where(x=>x.Sales>0);
所以,让我看看这些,当我设置我的交易属性时,我在前一行中设置了交易集合,现在我想用在前一行中分配的交易属性来设置我的销售属性:
Transactions= e.Transactions,
Sales = e.Transactions.Sum(x=>x.Quantity) // Normaly I'd do it like this
但我想尝试这样的事情:
Sales = Transactions.Sum(x=>x.Quantity) // is this doable ?
所以我的问题是,是否可以在select语句中使用先前的属性值设置另一个属性? 就我而言,它是交易集合?
如果可行,这可行吗?
PS我试图确定这是否可行,因为如果可以使用此先前设置的属性的value,那么我将避免对DB中的Transactions表执行2个不必要的查询?
您不能使用以前的值,因为您不想为每个项目调用e.Transactions.Sum()。
只需向MyViewModel添加一个方法
public double GetSales()
{
return Transactions.Sum(x=>x.Quantity);
}
//at the end of your code use:
.Where(x=>x.GetSales()>0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.