绝地无双
此类问题非常适合使用 LINQ。下面的 LINQ 查询首先创建不同日期和品牌名称的外连接。这为我们提供了全天可以加入的所有品牌的列表。这样,每个品牌都会有相同的天数,即使它在某一天从未售出任何商品。然后,它会根据该品牌/日期列表加入购买,如果当天没有记录该品牌的购买,则会使用 来创建零成本/数量的替代购买DefaultIfEmpty。然后,该连接的结果将被投影到对象列表中BrandsProfit。例如,如果某一天没有购买某个品牌,您会注意到在示例数据列表中,“2”天的品牌“B”被注释掉了;但在结果中,“2”天仍然存在品牌“B”的行,每日总利润为零。void Main(){ var purchases = new List<Purchase>() { new Purchase() { BrandName = "A", CostOfItem = 1.13M, Day = 1, TotalPurchased = 125 }, new Purchase() { BrandName = "B", CostOfItem = 1.52M, Day = 1, TotalPurchased = 165 }, new Purchase() { BrandName = "C", CostOfItem = 1.90M, Day = 1, TotalPurchased = 836 }, new Purchase() { BrandName = "A", CostOfItem = 1.74M, Day = 2, TotalPurchased = 583 }, //new Purchase() { BrandName = "B", CostOfItem = 1.52M, Day = 2, TotalPurchased = 785 }, new Purchase() { BrandName = "C", CostOfItem = 1.42M, Day = 2, TotalPurchased = 369 }, new Purchase() { BrandName = "A", CostOfItem = 1.93M, Day = 3, TotalPurchased = 789 }, new Purchase() { BrandName = "B", CostOfItem = 1.87M, Day = 3, TotalPurchased = 739 }, new Purchase() { BrandName = "C", CostOfItem = 1.78M, Day = 3, TotalPurchased = 436 }, }; var results = from day in purchases.Select(x => x.Day).Distinct() from brand in purchases.Select(x => x.BrandName).Distinct() join purchase in purchases on new { Brand = brand, Day = day } equals new { Brand = purchase.BrandName, Day = purchase.Day } into j from result in j.DefaultIfEmpty(new Purchase() { BrandName = brand, Day = day, TotalPurchased = 0, CostOfItem = 0 }) select new BrandsProfit() { BrandName = result.BrandName, Day = result.Day, TotalDailyProfit = result.TotalPurchased * result.CostOfItem }; Debug.WriteLine(JsonConvert.SerializeObject(results, Newtonsoft.Json.Formatting.Indented));}class Purchase{ public string BrandName { get; set; } public int Day { get; set; } public int TotalPurchased { get; set; } public decimal CostOfItem { get; set; }}class BrandsProfit{ public string BrandName { get; set; } public int Day { get; set; } public decimal TotalDailyProfit { get; set; }}产生以下结果:-[ { "BrandName": "A", "Day": 1, "TotalDailyProfit": 141.25 }, { "BrandName": "B", "Day": 1, "TotalDailyProfit": 250.80 }, { "BrandName": "C", "Day": 1, "TotalDailyProfit": 1588.40 }, { "BrandName": "A", "Day": 2, "TotalDailyProfit": 1014.42 }, { "BrandName": "B", "Day": 2, "TotalDailyProfit": 0.0 }, { "BrandName": "C", "Day": 2, "TotalDailyProfit": 523.98 }, { "BrandName": "A", "Day": 3, "TotalDailyProfit": 1522.77 }, { "BrandName": "B", "Day": 3, "TotalDailyProfit": 1381.93 }, { "BrandName": "C", "Day": 3, "TotalDailyProfit": 776.08 }]如果您不想继续使用上面的示例,您可以考虑更新用于生成数据的源查询,以purchaseQuery使用像上面这样的外连接...这样您就会有一个行代表品牌/天的每个组合,即使某个品牌从未在特定日期销售过。