使用LINQ
var totalQty = 0; foreach (var item in ItemIDList) { var sumOfCurrentItem = GrnList.SelectMany(s => s.GRNDetails .Where(f => f.ItemID == item)).Select(f => f.RecevedQty).Sum(); totalQty += sumOfCurrentItem ; }
或者甚至是一个衬里更换 foreach
循环(Credit转到ReSharper :))
int totalQty = ItemIDList.Sum(item => GrnList .SelectMany(s => s.GRNDetails.Where(f => f.ItemID == item)) .Select(f => f.RecevedQty).Sum());