我有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;}
}
我需要显示每个“客户”的不同“SalesID”的列表,其中金额大于> 0这年是今年。
目前,我正在按客户分组,但因为我的数据集中的同一个Customer和SalesID可以有多个“Amounts”,所以我没有得到我期望的结果。我的结果显示:
但我想要的是
这是我的表达:
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;
答案 0 :(得分:2)
我认为如果您更改查询以便拥有“外部”GroupBy
和“内部”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;
答案 1 :(得分: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#编译器,因此可能存在一些错误。
这里问题的关键在于你需要汇总你的金额总和。