如何使这个LINQ查询更干净?

A S*_*edo 1 c# linq refactoring linq-to-sql

我最近编写了一个LINQ查询来获取Dictionary包含最近6个月的展示位置金额.

它返回Dictionary月份字符串 - 十进制金额对.

这似乎是一种喧嚣.你们中的任何一位LINQ大师都能帮助我重构这个以使它更干净一点吗?

/// <summary>
/// Gets the last 6 months of Placement History totalled by Month 
/// for all Agencies
/// </summary>
/// <returns></returns>
public Dictionary<string, decimal> getRecentPlacementHistory()
{
    var placementHistoryByMonth = new Dictionary<string, decimal>();

    using (DemoLinqDataContext db = new DemoLinqDataContext())
    {
        for (int i = 0; i < 6; i++)
        {
            Decimal monthTotal = 
              (from a in db.Accounts
               where 
                 (a.Date_Assigned.Value.Month == DateTime.Now.AddMonths(-i).Month &&
                  a.Date_Assigned.Value.Year == DateTime.Now.AddMonths(-i).Month)
               select a.Amount_Assigned).Sum();
            String currentMonth = DateTime.Now.AddMonths(-i).ToString("MMM");

            placementHistoryByMonth.Add(currentMonth, monthTotal);
        }
        return placementHistoryByMonth;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

第一个问题:

where (a.Date_Assigned.Value.Month == DateTime.Now.AddMonths(-i).Month &&
       a.Date_Assigned.Value.Year == DateTime.Now.AddMonths(-i).Month)
Run Code Online (Sandbox Code Playgroud)

后面的表达不应该以.Year而不是.Month结束吗?当然你很少会得到一年的价值1-12 ......

当你正在使用它时,我会提取"当前月份"的想法.请注意,您还要多次使用当前时间,如果它在月底的午夜运行,可能会产生奇怪的结果......

public Dictionary<string, decimal> getRecentPlacementHistory()
{
    var placementHistoryByMonth = new Dictionary<string, decimal>();
    using (DemoLinqDataContext db = new DemoLinqDataContext())
    {
        DateTime now = DateTime.Now;

        for (int i = 0; i < 6; i++)
        {
            DateTime selectedDate = now.AddMonths(-i);

            Decimal monthTotal = 
               (from a in db.Accounts
                where (a.Date_Assigned.Value.Month == selectedDate.Month &&
                       a.Date_Assigned.Value.Year == selectedDate.Year)
                select a.Amount_Assigned).Sum();

            placementHistoryByMonth.Add(selectedDate.ToString("MMM"),
                                        monthTotal);
        }
        return placementHistoryByMonth;
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到这可能是你试图摆脱的循环.您可以尝试计算整批日期的上限和下限,然后按a.Date_Assigned相关范围内的年/月进行分组.说实话,它并不会更漂亮.请注意,如果您可以将其关闭,那只会对数据库进行一次查询.