Forget most learnt about linq,now need to review what is it. And how it works.now I need help for this. Please help me .Thank you so much.
var everyMonthMoneySum = new EveryMonthMoneySum()
{
M_01 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 1)
select o.Signmoney).Sum(),
M_02 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 2)
select o.Signmoney).Sum(),
M_03 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 3)
select o.Signmoney).Sum(),
M_04 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 4)
select o.Signmoney).Sum(),
M_05 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 5)
select o.Signmoney).Sum()+5,
...........................
M_11 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 11)
select o.Signmoney).Sum(),
M_12 = (from o in temp.Where(o => o.IsSign == (short) OrderStateEnum.Success && o.SignMonth == 12)
select o.Signmoney).Sum()
};
It sounds to me like you could do with a dictionary:
var results = temp.Where(o => o.IsSign == (short) OrderStateEnum.Success)
.GroupBy(o => o.SignMonth)
.ToDictionary(g => g.Key, g => g.Sum(o => o.SignMoney));
Note that that won't populate the dictionary with entries for "missing" months.
That will give you a single collection, instead of 12 different variables. Personally I find that's usually a better approach, but we don't really know what you're trying to do with those 12 values...
If you want to make sure the dictionary is populated, I would personally do that with an extra loop afterwards:
for (int i = 1; i <= 12; i++)
{
if (!results.ContainsKey(i))
{
results[i] = 0m;
}
}
It's not "clever", but it works. Alternatively, you could populate an array from the dictionary:
var array = new decimal[13]; // 0 to 12 *inclusive*
foreach (var entry in array)
{
array[entry.Key] = entry.Value;
}
There are other ways of doing it all in the LINQ statement, but I don't know how they'd play with whatever LINQ provider you're using (we don't know) and they're more complex.
See more on this question at Stackoverflow