【发布时间】:2015-11-07 02:10:25
【问题描述】:
我有这门课:
public class ItemsForMonthYear
{
public String ItemDescription { get; set; }
public String monthYr { get; set; }
public int TotalPackages { get; set; }
public Decimal TotalPurchases { get; set; }
public Decimal AveragePrice { get; set; }
public Double PercentOfTotal { get; set; }
}
...我存储数据的地方。我有一个用于存储其中 N 个的通用列表:
List<ItemsForMonthYear> itemsForMonthYearList;
...然后我从该列表中读取以填充电子表格,这非常简单:
totPackagesCell.Value2 = ifmy.TotalPackages;
totPurchasesCell.Value2 = ifmy.TotalPurchases;
avgPriceCell.Value2 = ifmy.AveragePrice;
...但所需的下一个单元格 val 是根据给定月份的所有 TotalPurchases 值计算得出的。因此,我需要为具有相同月值的所有 ItemsForMonthYear “记录”计算“总百分比”值。在 SQL 中,我可以这样做:
SELECT SUM(TotalPurchases) FROM ItemsForMonthYear WHERE monthYr = 'Apr 14'
...然后将该结果除以每个 ItemDescription 的 TotalPurchases 值
IOW,如果“4 月 14 日”月份的所有 TotalPurchases 总和为 100 万美元,并且 ItemDescription“Cocoa Puffs”的 TotalPurchases 为 10 万美元,我可以计算“Cocoa Puffs”的 PercentOfTotal 为为 10%。
我可以“暴力破解”并遍历整个通用列表:
Decimal allTotalPurchases;
foreach (ItemsForMonthYear ifmy in itemsForMonthYearList)
{
if (ifmy.monthYr.Equals("Apr 14")
{
allTotalPurchases = allTotalPurchases + ifmy.TotalPurchases;
}
}
...但我认为有一种更优雅/性能更友好的方式可以使用 LINQ 完成此任务。我想做这样的事情:
percentOfTotalCell.Value2 = GetPercentForPurchaseForMonthYearAsStr(ifmy.TotalPurchases, curMonth);
private String GetPercentForPurchaseForMonthYearAsStr(decimal totPurchasesForItemMonthYear, string totPurchasesForMonthYear)
{
percentOfTotal = // What LINQ magic goes here?
percentOfTotalStr = percentOfTotal.ToString("P", CultureInfo.InvariantCulture);
return percentOfTotalStr;
}
...其中 arg "totPurchasesForItemMonthYear" 将是上面示例中的十万美元等值,而 arg "totPurchasesForMonthYear" 将是值例如“4 月 14 日”。
有谁知道这个聪明的 LINQ 技巧?
【问题讨论】: