c# - 我怎样才能使这个 LINQ 查询更清晰?

标签 c# linq linq-to-sql refactoring

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

它返回月份字符串的 Dictionary - Decimal Amount 对。

看起来有点笨拙。有哪位 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;
    }
}

最佳答案

第一个问题:

where (a.Date_Assigned.Value.Month == DateTime.Now.AddMonths(-i).Month &&
       a.Date_Assigned.Value.Year == DateTime.Now.AddMonths(-i).Month)

后一个表达式不应该以 .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;
    }
}

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

关于c# - 我怎样才能使这个 LINQ 查询更清晰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1018975/

相关文章:

c# - 如何在 "website"模式下使用 ResourceManager?

C# 从给定接口(interface)的字符串实例化类

c# - LINQ:如何清空投影中的属性?

C#在删除重复的子字符串后获取第一整行

c# - 有没有办法跟踪数据上下文何时访问数据库?

c# - 窗口刷新音频

c# - System.Drawing 可以在 Azure 网站中使用吗?

c# - 通过 LINQ 检查 XML 中每个子项中的重复值

c# - 使用linq通过两个表中的多列进行简单连接的问题

c# - LINQ2SQL 非重复计数和排序