3

我有一个列表,ForecastData它看起来像这样:

public class ForecastData
{
    public string SalesID {get;set;}
    public string Customer {get;set;}
    public string Vendor {get;set;}
    public string Division {get;set;}
    public int Year {get;set;}
    public decimal Amount {get;set;}
}

我需要为金额 > 0 的每个“客户”显示每个不同的“销售 ID”的列表,其中年份是今年。

目前,我正在按客户分组,但因为我的数据集中可以为同一个客户和 SalesID 有多个“金额”,所以我没有得到我期望的结果。我的结果显示:

  1. 客户 1 用户 1 $100
  2. 客户 1 用户 1 $200
  3. 客户 1 用户 1 $300
  4. 客户 1 用户 2 100 美元
  5. 客户 1 用户 2 $200

但我想要的是

  1. 客户 1 用户 1 $600
  2. 客户 1 用户 2 300 美元

这是我的表达:

var forecasts = (List<ForecastData>)cache.Get(_RAW_FORECAST_DATA_KEY, null);

foreach(var custGroup in forecasts.Where(f => f.Year == DateTime.Now.Year).GroupBy(f => f.Customer))
{
    if(custGroup.Count() > 1) // There's more than one forecast for this customer
    {
        foreach(var instance in custGroup)
        {
            toReturn.Add(new MultipleCustomer(custGroup.Key)
            {
                Salesperson = instance.SalesPersonId,
                Forecast = instance.Amount
            });
        }
    }
}

return toReturn;
4

2 回答 2

2

我想如果你改变你的查询,让你有一个 "outer"GroupBy和一个 "inner" GroupBy,它会解决你的问题:

var forecasts = (List<ForecastData>)cache.Get(_RAW_FORECAST_DATA_KEY, null);

var forecastGroups = forcasts
    .Where(f => f.Year = DateTime.Now.Year)
    .GroupBy(f => f.Customer)
    .Where(grp => grp.Count() > 1)
    .Select(grp => new { Key = grp.Key, SalesGroups = grp.GroupBy(f => f.SalesId) });

foreach(var custGroup in forecastGroups)
{
    if(custGroup.SalesGroups.Count() > 1)
    {
        foreach(var salesGroup in custGroup.SalesGroups)
        {
            toReturn.Add(new MultipleCustomer(custGroup.Key)
            {
                Salesperson = salesGroup.Key,
                Forecast = salesGroup.Sum(f => f.Amount)
            });
        }
    }
}

return toReturn;
于 2012-11-20T21:43:47.123 回答
2

尝试以下操作:

foreach(var custGroup in forecasts.Where(f => f.Year == DateTime.Now.Year).GroupBy(f => new { f.Customer, f.SalesPersonId }).Where(k => k.Count() > 1).Select(k => new { Customer = k.Key.Customer, SalesPersonId = k.Key.SalesPersonId, TotalAmount = k.Sum(x => x.Amount) } )
{
           toReturn.Add(new MultipleCustomer(custGroup.Customer)
           {
              Salesperson = custGroup.SalesPersonId,
              Forecast = custGroup.TotalAmount
           });
       }
   }
}

我一直在写它。附近没有 C# 编译器,因此可能会出现一些错误。

您的问题的关键是您需要汇总您的项目总和他们的金额。

于 2012-11-20T22:07:40.123 回答