计算列表<class>中列的总和

时间:2017-08-03 17:28:09

标签: c# sql-server linq

我正在尝试计算传递的项目参数的timecard类中的小时数。我对LINQ,MVC,导航属性和Lambda表达式都足够新,我一直在追逐我的尾巴试图让它在我的ViewModel构造函数中运行。

我有以下内容: ProjectTimecardViewModel.cs

public class ProjectTImecardViewModel
{
    public int? ProjectId { get; set; }
    public string ProjectName { get; set; }
    public decimal TotalHours { get; set; }
    public List<Timecard> Timecards { get; set; }

    public ProjectTImecardViewModel(Project project)
    {
        ProjectId = project.ProjectId;
        ProjectName = project.ProjectName;
        Timecards = project.Timecards;

        //equivalent of what I want in SQL
        // TotalHours = SELECT SUM(Hours) FROM [Timecards] WHERE ProjectId = @ProjectId
        // best guess at what I want in LINQ
        // TotalHours = (from hours in Timecards where ProjectId == project.ProjectId select hours).Sum();
    }
}

Timecard.cs

public class Timecard
{
    public int TimecardId { get; set; }
    public int EmployeeId { get; set; }
    public DateTime Date { get; set; }
    public int TaskId { get; set; }
    public decimal Hours { get; set; }
    public int? ProjectId { get; set; }
    public Employee Employee { get; set; }
    public Project Project { get; set; }
    public TimecardTask TimecardTask { get; set; }
}

Project.cs

public class Project
{
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }
    ...
    public List<Timecard> Timecards { get; set; }

    public Project()
    {
        Timecards = new List<Timecard>();
    }
}

我知道我可以创建一个初始化我的dbContext的类,并以这种方式找出等效的LINQ语法,但是我知道如何做的唯一方法是在代码中公开我的连接字符串。对于它的价值,这是代码优先的EF Core连接到MSSQL服务器。

我知道这个语法并不完全正常,但是我可以使用现有的导航属性或现有类的TotalHours = (from hours in Timecards.Hours where ProjectId == project.ProjectId select hours).Sum();上的lambda表达式吗?因为我在小时下得到红色的波浪线,因为列表不包含小时的定义。或者还有另一种方法可以制作一个小时列表并运行上面的LINQ吗?

1 个答案:

答案 0 :(得分:2)

我想你只想使用Sum

TotalHours = Timecards.Sum(c => c.Hours);

或者,如果您需要项目ID片段:

TotalHours = Timecards.Where(c => c.ProjectId == ProjectId).Sum(c => c.Hours);

尝试将其纳入查询语法可能并不值得。