求助,一个linq的查询问题

详见代码

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; }

}


慕桂英4014372
浏览 747回答 1
1回答

慕哥6287543

var&nbsp;result&nbsp;=&nbsp;(from&nbsp;x&nbsp;in&nbsp;scoreList&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where&nbsp;x.Score&nbsp;<&nbsp;userScore &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;group&nbsp;x&nbsp;by&nbsp;x.Score&nbsp;into&nbsp;g&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;orderby&nbsp;g.Key&nbsp;descending&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;select&nbsp;g).First(); //或者用var result2 = scoreList.Where(x => x.Score < userScore)&nbsp; &nbsp; &nbsp; &nbsp;.GroupBy(x => x.Score)&nbsp; &nbsp; &nbsp; &nbsp;.OrderByDescending(g => g.Key)&nbsp; &nbsp; &nbsp; &nbsp;.First();
打开App,查看更多内容
随时随地看视频慕课网APP