Linq:如何使用一行代码轻松实现这一目标?

时间:2015-05-11 16:23:27

标签: c# linq

忘了最了解linq,现在需要回顾一下它是什么。它是如何工作的。现在我需要帮助。请帮帮我。非常感谢你。

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()

};

2 个答案:

答案 0 :(得分:2)

听起来像你可以用字典做的那样:

var results = temp.Where(o => o.IsSign == (short) OrderStateEnum.Success)
                  .GroupBy(o => o.SignMonth)
                  .ToDictionary(g => g.Key, g => g.Sum(o => o.SignMoney));

请注意,赢了填充字典,其中包含"缺少"个月。

这将为您提供一个集合,而不是12个不同的变量。就个人而言,我发现这通常是一种更好的方法,但我们真的不知道你试图用这12个值做什么...

如果你想确保填充字典,我会个人之后再做一次额外的循环:

for (int i = 1; i <= 12; i++)
{
    if (!results.ContainsKey(i))
    {
        results[i] = 0m;
    }
}

它不是&#34;聪明&#34;,但它有效。或者,您可以从字典中填充数组:

var array = new decimal[13]; // 0 to 12 *inclusive*
foreach (var entry in array)
{
    array[entry.Key] = entry.Value;
}

在LINQ语句中还有其他方法可以完成所有操作,但我不知道他们如何使用您正在使用的任何LINQ提供程序(我们都不知道)而且他们更复杂。

答案 1 :(得分:1)

使用GroupByWhere过滤掉值,然后按SignMonth分组,如:

var query = temp.Where(o => o.IsSign == (short) OrderStateEnum.Success)
    .GroupBy(r => r.SignMonth)
    .Select(grp => new
    {
        Month = grp.Key,
        Sum = grp.Sum(t => t.Signmoney)
    });