列表中的最大值小于X.

Tag*_*eit 4 c# linq

如何从中检索intList是最大数,但仍小于X我所比较的值.

Value = 10

Example one: List = {1,4,6,8};  => number 8 biggest on list and smaller than 10
Example two: List = {1,15,17,20}; => number 1 biggest on list and smaller than 10
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Linq但到目前为止没有成功.

Gra*_*ICA 13

您可以使用Where子句限制用于获取"Max"的值:

return myList.Where(x => x < 10).Max();
Run Code Online (Sandbox Code Playgroud)

  • `MyLoc.Where(s => s.CurrentLoc <10).Max()`抛出一个错误,因为它不知道什么是"Max",这不是你问的问题,因为你的列表只是有整数.你想要`MyLoc.Where(s => s.CurrentLoc <10).Max(s => s.CurrentLoc)`来获得10以下的最大`CurrentLoc`或者'MyLoc.Where(s => s. CurrentLoc <10).OrderByDescending(s => s.CurrentLoc).First()`得到一个带有这样一个'CurrentLoc`的​​项目,但这个答案对于最初提出的问题是完美的. (2认同)