I have a table name GRNDtlReturn
in above mention screenshot. I want to get the sum of ReturnQuantity
of first and third rows in table. I have written some code, but it returns the sum of full ReturnQuantity
column. Please help me to solve this.
Here's my code:
public IList<GRNDtlReturnModel> GetReturnSum()
{
return igrndtlreturnRepository.GetList (x=> x.GRNNo == "GRN00022" && x.ProductCode == "D/F/HL/DM/0003/C/002")
.Select(y => new GRNDtlReturnModel
{
GRNNo = y.GRNNo,
totalQuantity = context.GRNDtlReturns.Sum(p => p.ReturnQuantity)
}).ToList();
}
public IList<GRNDtlReturnModel> GetReturnSum()
{
return igrndtlreturnRepository.GetList(x=> x.GRNNo == "GRN00022" &&
x.ProductCode == "D/F/HL/DM/0003/C/002")
.Select(y => new GRNDtlReturnModel
{
GRNNo = y.GRNNo,
totalQuantity = context.GRNDtlReturns.
Where(t=> t.GRNNo==y.GRNNo).Sum(p => p.ReturnQuantity)
}).ToList();
}
I assume that igrndtlreturnRepository.GetList(x => x.GRNNo == grnno && x.ProductCode == productcode)
returns an IQueryable<GRNDtlReturn>
according to the filter expression.
Case 1: Get a single result for GRNNo = "GRN00022"
and ProductCode = "D/F/HL/DM/0003/C/002"
In this case, the result of GetList
is already limited to the relevant entries and there should be a single result GRNDtlReturnModel
if any row matches the criteria.
GRNDtlReturnModel result = igrndtlreturnRepository.GetList(x => x.GRNNo == "GRN00022" && x.ProductCode == "D/F/HL/DM/0003/C/002")
.GroupBy(x => x.GRNNo, (k, v) => new GRNDtlReturnModel { GRNNo = k, totalQuantity = v.Sum(q => q.ReturnQuantity) })
.FirstOrDefault();
Case 2: Get the group-sum for all matching combinations of GRNNo
and ProductCode
In this case, the grouping expression needs to contain all relevant group keys, the calculation of sum stays the same.
IList<GRNDtlReturnModel> result = igrndtlreturnRepository.GetList(x => true)
.GroupBy(x => new { x.GRNNo, x.ProductCode }, (k, v) => new GRNDtlReturnModel { GRNNo = k.GRNNo, totalQuantity = v.Sum(q => q.ReturnQuantity) })
.ToList();
This should be more efficient than a nested access to context.GRNDtlReturns
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.