详见代码
static void Main(string[] args) { List<ScoreModel> scoreList = new List<ScoreModel>(){ new ScoreModel(){Id = 1, Score = 30}, new ScoreModel(){Id = 2, Score = 20}, new ScoreModel(){Id = 3, Score = 30}, new ScoreModel(){Id = 4, Score = 20}, new ScoreModel(){Id = 5, Score = 15}, new ScoreModel(){Id = 6, Score = 10}, new ScoreModel(){Id = 7, Score = 30}, new ScoreModel(){Id = 8, Score = 40}, }; int userScore = 33; var result = from i in scoreList where [how to?] select i; //获取i.score小于userScore的最大值 //即所有小于33的列表中取出最大值30的3个元素 //期望结果:包含三个元素id=1,3,7的List<ScoreModel> } class ScoreModel { public int Id { get; set; } public int Score { get; set; } }
var result = (from x in scoreList where x.Score < userScore group x by x.Score into g orderby g.Key descending select g).First();
//或者用
var result2 = scoreList.Where(x => x.Score < userScore)
.GroupBy(x => x.Score)
.OrderByDescending(g => g.Key)
.First();
可以先选出小于33的最大score,然后再二次查询
// List<ScoreModel> result = scoreList.Where(w => w.Score < userScore).GroupBy(g => g.Score).OrderByDescending(o => o.Key).First().ToList(); // int max=scoreList.Where(w => w.Score < userScore).Max(m=>m.Score); List<ScoreModel> result1= scoreList.Where(w => w.Score==max).ToList();
var query = from item in scoreList where item.Score < userScore orderby item.Score descending select item; var max = query.Max(c => c.Score); var result = query.Where(c => c.Score == max);
先排序一下,然后first(l=>l.score>你指定的值)
scoreList.Where(query => query.Score ==
scoreList.Where(query1 => query1.Score < userScore).Max(query3=>query3.Score)).ToList()
var result = (from i in scoreList where i.Score<userScore orderby i.Score descending select i).Take(3).ToList();
var result = scoreList.Where(r => r.Score == scoreList.Where(c => c.Score < userScore).Max(c => c.Score));
var result = scoreList.Where (m=>m.Score<userScore).OrderByDescending(m=>m.Score).Take(3);
result.Dump();