来自LINQ的结果,包含用于TimeSpan,GROUP和JOIN的SUM

时间:2012-11-21 09:28:35

标签: c# linq entity-framework group-by sum

我关注EF模型:

enter image description here

我想在以下视图中获取数据:

enter image description here

在数据实体中,Time是Timespan,以毫秒为单位。结果,PlaceInStep位于成员之间StepId

如何进行此次硬查询?

修改1

我的一些代码:

var query = from data in ctx.Data
                            join member in ctx.Members
                            on data.MemberId equals member.MemberId
                            join team in ctx.Teams
                            on member.TeamId equals team.TeamId
                            group member by member.TeamId into g
                            select new {TeamId = g.Key, TeamName = g.Select(t=>t.Teams.TeamName), TotalTime = ???};

2 个答案:

答案 0 :(得分:3)

一开始的建议。您不应该在查询中使用join。您的模型具有导航属性,请改用它们。你可以阅读Craig Stuntz关于它的blogpost

您可以选择内部列表中所有成员和有关成员的信息。试试这个:

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 :(得分:1)

试试这个:

var query = ctx.Data.Join(ctx.Members, d => d.MemberId, m => m.MemberId, (d,m)=>new {data=d, member = m})
                .Join(ctx.Teams, dm=>dm.member.TeamId, t=>t.TeamId, (dm, t)=>new{data=dm.data, member=dm.member, team = t})
                .GroupBy(dmt=>new {dmt.team.TeamId, dmt.team.TeamName})
                .Select(g=>new 
                           {
                               TeamId = g.Key.TeamId, 
                               TeamName = g.Key.TeamName, 
                               TotalTime = g.Aggregate(0, (sum, gr)=>sum.Add(gr.data.Time))
                           });