首页新闻找找看学习计划

求助,一个linq的查询问题

0
悬赏园豆:10 [已解决问题] 解决于 2018-08-29 18:58

详见代码

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; }
}
wdwwtzy的主页 wdwwtzy | 菜鸟二级 | 园豆:226
提问于:2012-10-12 11:42
< >
分享
最佳答案
0
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();

收获园豆:10
水牛刀刀 | 大侠五级 |园豆:6350 | 2012-10-12 14:56
其他回答(8)
0

可以先选出小于33的最大score,然后再二次查询

清海扬波 | 园豆:813 (小虾三级) | 2012-10-12 11:51
0
            //
            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();
Qlin | 园豆:2403 (老鸟四级) | 2012-10-12 12:37
0
 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);
@索卡 | 园豆:140 (初学一级) | 2012-10-12 12:59
0

先排序一下,然后first(l=>l.score>你指定的值)

chenping2008 | 园豆:9836 (大侠五级) | 2012-10-12 13:27
0

scoreList.Where(query => query.Score ==
        scoreList.Where(query1 => query1.Score < userScore).Max(query3=>query3.Score)).ToList()

forhells | 园豆:969 (小虾三级) | 2012-10-13 11:09
0
var result = (from i in scoreList
               where i.Score<userScore
               orderby i.Score descending
               select i).Take(3).ToList();
博爸 | 园豆:220 (菜鸟二级) | 2012-10-13 12:39
0
            var result = scoreList.Where(r => r.Score == scoreList.Where(c => c.Score < userScore).Max(c => c.Score));
RyanCheng | 园豆:474 (菜鸟二级) | 2012-11-29 09:56
0

var result = scoreList.Where (m=>m.Score<userScore).OrderByDescending(m=>m.Score).Take(3);
result.Dump();

Iasffcel | 园豆:202 (菜鸟二级) | 2012-12-04 11:09
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册