我试图按项目ID进行分组,以便可以返回一个总和,但是当我尝试使用First()返回字段的值时,它仅返回一个值。
ASP.net c#项目试图返回一个字段的总和,我有使用LINQ返回正确数字的代码,但是我似乎无法返回相应的字符串字段。我尝试按2个字段进行分组,但这会返回太多记录。
public class JobsByDrivetime
{
private string pid;
private double jobMinutes;
private string jobEventType;
public JobsByDrivetime(string pid, double jobMinutes,string jobEventType)
{
this.pid = pid;
this.jobMinutes = jobMinutes;
this.jobEventType = jobEventType;
}
public string Pid
{
get { return pid; }
set { pid = value; }
}
public double JobMinutes
{
get { return jobMinutes; }
set { jobMinutes = value; }
}
public string JobEventType
{
get { return jobEventType; }
set { jobEventType = value; }
}
}
List<JobsByDrivetime> ProjectbyDrivetime = new List<JobsByDrivetime>();
ProjectbyDrivetime.Add(new JobsByDrivetime("0186975-0001", 439, "HR"));
ProjectbyDrivetime.Add(new JobsByDrivetime("0186975-0001", 100, "HR"));
ProjectbyDrivetime.Add(new JobsByDrivetime("0186975-0001", 180, "JR"));
var projectBydrivetimeList = ProjectbyDrivetime
.GroupBy(v => v.Pid) //(c => new { Pid = c.Pid, ProjectType = c.JobEventType })
.Select(g => new
{
Pid = g.Key,
ProjectMinutes = g.Sum(x => x.JobMinutes),
ProjectType=g.Select(x=> x.JobEventType).First()
}).ToList();
foreach (var D in projectBydrivetimeList)
{
shiftSummary.Add("<tr><td>" + D.Pid + "</td><td>" + D.ProjectType + "</td><td>" + D.ProjectMinutes + "</td></tr>");
}
输出
0186975-0001 HR 539
0186975-0001 HR 180
它正确地对ProjectMinutes进行了分组(按项目类型),但仅显示2个项目类型之一。我期望D.ProjectType在第一个成为HR,在第二个成为JR。我明白这是因为我正在使用First()。
答案 0 :(得分:0)
希望我能正确理解您的要求。出于对Group By Pid和ProjectType的考虑,您已经步入正轨。
var projectBydrivetimeList = ProjectbyDrivetime
.GroupBy(v => new {v.Pid,v.JobEventType})
.Select(g => new
{
Pid = g.Key.Pid,
ProjectMinutes = g.Sum(x => x.JobMinutes),
ProjectType=g.Select(x=> x.JobEventType).First()
}).ToList();
样本输出
更新
根据您的评论,另一个示例输入
输出