希望得到一些帮助。
我正在从数据库中检索以下列表。
Name AssessNumber Score
John 1 90
John 2 88
John 3 67
Steve 1 98
Steve 2 90
我想要的是按平均分数分组并显示最高分数(int)
Name AssessNumber Score
John 3 81.6
Steve 2 94
数据将存储在List<lbResults>lb = new List<lbResults>()
我怎样才能做到这一点?
亲切的问候
答案 0 :(得分:7)
试试这个:
var results = data.GroupBy(x => x.Name).Select(x => new
{
Name = x.Key,
AssessNumber = x.Max(z => z.AssessNumber),
Score = x.Average(z => z.Score)
})
您还可以返回原始数据结构(您命名为lbResults
):
var results = data.GroupBy(x => x.Name).Select(x => new lbResults
{
Name = x.Key,
AssessNumber = x.Max(z => z.AssessNumber),
Score = x.Average(z => z.Score)
})
请参阅Fiddle
答案 1 :(得分:2)
试试这个: -
List<lblResults> result = data.GroupBy(x => x.Name)
.Select(x => new lbResults
{
Name = x.Key,
AssessNumber = x.Max(z => z.AssesName),
Score = x.Average(s => s.Score)
}
).ToList();
答案 2 :(得分:2)
我想要按平均分数分组
从输出中看,您希望按Name
进行分组,并获得最高AssessNumber
和平均Score
。您的查询应该是:
var query = lb.GroupBy(r => r.Name)
.Select(grp => new
{
Name = grp.Key,
AccessNumber = grp.Max(i=> i.AccessNumber),
AverageScore = grp.Avg(i => i.Score),
});
答案 3 :(得分:2)
假设:
public class lbResults
{
public string Name { get; set; }
public int Assess { get; set; }
public int Score { get; set; }
}
你想要:
List<lbResults> lb = new List<lbResults>
{
new lbResults{ Name="John", Assess = 1, Score=90},
new lbResults{ Name="John", Assess = 2, Score=88},
new lbResults{ Name="John", Assess = 3, Score=67},
new lbResults{ Name="Steve", Assess = 1, Score=98},
new lbResults{ Name="Steve", Assess = 2, Score=90},
};
var results = lb.GroupBy(l => l.Name)
.Select(g => new
{
Name = g.Key,
Assess = g.Max(gr => gr.Assess),
Score = g.Average(gr => gr.Score)
});
答案 4 :(得分:0)
让我们有球员:
var players = new List<Player> {
new Player { Name = "John", AssessNumber = 1, Score = 90 },
new Player { Name = "John", AssessNumber = 2, Score = 88 },
new Player { Name = "John", AssessNumber = 3, Score = 67 },
new Player { Name = "Steve", AssessNumber = 1, Score = 98 },
new Player { Name = "Steve", AssessNumber = 2, Score = 90 },
};
此代码显示使用 linq查询表达式语法:
进行分组var playerInfos =
from player in players
group player by player.Name into playerGroup
select new
{
PlayerName = playerGroup.Key,
MaxAssessNumber = playerGroup.Max(x => x.AssessNumber),
AverageScore = playerGroup.Average(x => x.Score),
};
结果playerInfos
是匿名对象的集合:
{ PlayerName = "John", MaxAssessNumber = 3, AverageScore = 81.66666... }
{ PlayerName = "Steve", MaxAssessNumber = 2, AverageScore = 94.0 }
查看有关LINQ Average聚合方法的更多信息。