LINQ 的查询_联表、分组、排序

1.查询

var v = from s in db.Set<ScoreInfo>().ToList()
group s by s.subject into score
select new
{
 sub = score.Key,
 avg = score.Average(s => s.score),
 max = score.Max(s => s.score),
 min = score.Min(s => s.score),
 sum = score.Sum(s => s.score)
};

2.

//linq根据姓名分组查询
var name=from u in db.Set<UserInfo>().ToList()
 join s in db.Set<ScoreInfo>().ToList()
 on u.ID equals s.uid
 group s by u.UserName into score
 select new
 {
 UserName=score.Key,
 avg=score.Average(d=>d.score)

};

//lamdba 的方式
var lamdba_join= db.Set<ScoreInfo>().Join(db.Set<UserInfo>(),
  h => h.uid, f => f.ID, (a, b) =>
new { a.score, b.UserName }).ToList().GroupBy(g => g.UserName).
Select(s => new { avg=s.Average(a => a.score),name=s.Key });

3.根据科目分组查询并排序

//linq
var sub = from s in db.Set<ScoreInfo>().ToList()
group s by s.subject into score
orderby score.Average(a => a.score) descending
select new
{
sub=score.Key,
avg=score.Average(a=>a.score)

};

//lamdba
var la= db.Set<ScoreInfo>().ToList().GroupBy(g => g.subject).
Select(s => new { sub = s.Key, avg = s.Average(a => a.score) }).OrderBy(o=>o.avg);

上一篇:【php】php与mysql初体验


下一篇:my.工坊_ZZ