LINQ with SUM for TimeSpan,GROUP和JOIN for EF

时间:2012-11-23 16:18:05

标签: c# linq entity-framework

在我的EF模型中: enter image description here

我提出这个观点:

enter image description here

使用以下LINQ查询(在您的帮助下):

var query = ctx.data.ToList().OrderBy(d => d.Time).
     GroupBy(d => d.Members.StepId).
     SelectMany(g => g.Select((d, place) => new { Time = d.Time, Members = d.Members, PlaceInStep = place + 1 })).
     GroupBy(d => d.Members.TeamId).
     Select(g => new 
     {
         TeamId = g.Key, 
         Name = g.Select(d => d.Members.Teams.TeamName).First(),  
         Members = g.Select(d => new {Time = d.Time, PlaceInStep = d.PlaceInStep, MemberName = d.Members.MemberName}),                    
         TotalTime = g.Aggregate(new TimeSpan(), (sum, nextData) => sum.Add(nextData.Time))
     });

但我有两个问题:

1。如果同一步骤中的2个成员(例如35岁之前的成员)具有相同的时间长达毫秒,则他们必须具有相同的位置

2。在结果中的成员子集合中,我想通过StepId排列成员并显示StepName。

如何修改此查询?感谢。

修改1:

我想采取一些措施:

enter image description here

1 个答案:

答案 0 :(得分:1)

用于计算正确成员位置的SQL查询:

select *, DENSE_RANK() over (partition by StepId order by Time)
from Members m
join Data d on m.MemberId =d.MemberId

linq等价物采用现有的linq查询:

var query = context.Data.ToList()
    .OrderBy(d=>d.Time)
    .GroupBy(d => d.Members.StepId)
    .SelectMany(g => 
        g.OrderBy(d => d.Time)
        .GroupBy(d => d.Time)
        .SelectMany((x, place) => 
            x.Select(d => new { Time = d.Time, Members = d.Members, PlaceInStep = place + 1 })))
    .GroupBy(d => d.Members.TeamId)
    .Select(g => new
    {
        TeamId = g.Key,
        Name = g.Select(d => d.Members.Teams.TeamName).First(),
        Members = g.Select(d => 
            new 
            { 
                Time = d.Time, 
                PlaceInStep = d.PlaceInStep, 
                MemberName = d.Members.MemberName, 
                StepName = d.Members.Steps.StepName, 
                StepId = d.Members.Steps.StepId 
            }).OrderBy(x=>x.StepId),
        TotalTime = g.Aggregate(new TimeSpan(), (sum, nextData) => sum.Add(nextData.Time))
    });