gpt4 book ai didi

c# - 按月将一个列表拆分为多个 - C#、Linq

转载 作者:行者123 更新时间:2023-11-30 14:36:23 24 4
gpt4 key购买 nike

我有以下 Linq 查询:

List<MonthlySales> monthlySales = (from sale in Sales
group sale by new { sale.DateSold.Month, sale.Product.Shop } into ds
select new MonthlyTitleSales
{
Shop = ds.Select(it => it.Product.Shop).FirstOrDefault(),
Month = ds.Select(it => it.DateSold.Month).FirstOrDefault(),
Year = ds.Select(it => it.DateSold.Year).FirstOrDefault(),
USDNumberItemsSold = ds.Where(it => it.USDCut.HasValue).Where(it => it.USDCut != 0).Count(),
GBPNumberItemsSold = ds.Where(it => it.GBPCut.HasValue).Where(it => it.GBPCut != 0).Count(),
EURNumberItemsSold = ds.Where(it => it.EURCut.HasValue).Where(it => it.EURCut != 0).Count(),
USDRevenueTotal = PerformCurrencyConversion(ds.Sum(it => it.USDCut.HasValue ? it.USDCut.Value : 0), 0M, 0M, Currency, endDate),
GBPRevenueTotal = PerformCurrencyConversion(0M, ds.Sum(it => it.GBPCut.HasValue ? it.GBPCut.Value : 0), 0M, Currency, endDate),
EURRevenueTotal = PerformCurrencyConversion(0M, 0M, ds.Sum(it => it.EURCut.HasValue ? it.EURCut.Value : 0), Currency, endDate),
}).OrderBy(it => it.DateSold.Month).ToList();

此查询为我提供了一个列表,每个列表项中包含以下元素:商店、月、年、收入

我最终需要做的是计算每个月所有商店的收入中位数,因此我需要以允许我这样做的方式准备好数据。

我认为一种方法可能是按月将此列表分成小列表,但我怀疑这是最有效的解决方案。

有没有人对此有任何想法?

任何需要查看的人的每月销售类(class):

public class MonthlySales
{
public int Month { get; set; }
public int Year { get; set; }

public Shop Shop { get; set; }

public int USDNumberItemsSold { get; set; }
public int GBPNumberItemsSold { get; set; }
public int EURNumberItemsSold { get; set; }
public int TotalNumberItemsSold { get { return USDNumberItemsSold + GBPNumberItemsSold + EURNumberItemsSold; } }

public decimal USDRevenueTotal { get; set; }
public decimal GBPRevenueTotal { get; set; }
public decimal EURRevenueTotal { get; set; }
public decimal OverallEarnings { get { return USDRevenueTotal + GBPRevenueTotal + EURRevenueTotal; } }
}

最佳答案

您可以使用 GroupBy 将列表按月分组。例如,以下将按月(实际上是月+年)分组,然后每月将所有值写入控制台:

var grouped = monthlySales.GroupBy(ms => string.Format("{0}-{1}", ms.Month, ms.Year));

foreach(var group in grouped)
{
Console.WriteLine("Values in month-year of {0}:", group.Key);
foreach(var ms in group)
Console.WriteLine(" {0}", ms.USDRevenueTotal);
}

关于c# - 按月将一个列表拆分为多个 - C#、Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com