在linq中获取多个不同的分组值

时间:2016-09-20 06:34:32

标签: c# .net linq distinct

Haven能够专门找到我的问题的答案..

我需要获得一个显示的结果:项目名称ONCE,包含在该项目中已在timeEntries生成的所有用户,在给定的日期范围内。

我还需要获得timeEntrieshoursEntered),这样我就可以计算出该项目花了多少小时......

我是新手,所以我希望我提供了足够的信息..

我的代码:

var dateStart = new DateTime (2016,09,01);
var dateEnd   = new DateTime (2016,09,19);

var query = (from timeEntry in TimeEntries
        join task in Tasks on timeEntry.TaskID equals task.TaskID
        join project in Projects on task.ProjectID equals project.ProjectID
        where timeEntry.DateEntity >= dateStart && timeEntry.DateEntity <= dateEnd
        select new {
        User = timeEntry.User.FirstName + " "+timeEntry.User.LastName,
        Project = timeEntry.Task.Project.ProjectName,
        ProjectId = timeEntry.Task.ProjectID,
        HoursEntered = timeEntry.HoursEntered
        }).GroupBy (q => q.Project).Distinct();

我有4张桌子:

  • 项目(ProjectID,ProjectName)
  • 任务(TaskID,ProjectID)
  • TimeEntries(HoursEntered,DateEntity,TaskID)
  • 用户(FirstName,LastName)

2 个答案:

答案 0 :(得分:2)

var query =
  from timeEntry in TimeEntries
  where timeEntry.DateEntity >= dateStart && timeEntry.DateEntity <= dateEnd
  select new {
    User = timeEntry.User.FirstName + " "+timeEntry.User.LastName,
    Project = timeEntry.Task.Project.ProjectName,
    ProjectId = timeEntry.Task.ProjectID,
    HoursEntered = timeEntry.HoursEntered
  }

var localRows = query.ToList();

var groups = localRows.GroupBy(x => x.Project);

var projects = groups.Select(g => new {
  Project = g.Key,
  Hours = g.Sum(x => x.HoursEntered),
  Users = g.Select(x => x.User).Distinct().ToList()
}).ToList();

答案 1 :(得分:1)

可能与:

var query = (from timeEntry in TimeEntries
        join task in Tasks on timeEntry.TaskID equals task.TaskID
        join project in Projects on task.ProjectID equals project.ProjectID
        where timeEntry.DateEntity >= dateStart && timeEntry.DateEntity <= dateEnd
        group timeEntry by new { proyect.ProjectID, proyect.ProjectName } into g
        select new {
        TimeEntries = g.ToArray(),
        Project = g.Key.ProjectName ,
        ProjectId = g.Key.ProjectID,
        HoursEntered = g.Sum(e => e.HoursEntered)
        });

我需要更多信息来调整它,但我认为这应该对你有帮助。我在浏览时做到了,所以mybe你需要检查名字。

Group by in LINQ