I need to sort in my studentsWatHighestDebts variable of type var (List) from students only those objects that matter in s.ZachetDidNotPass maximum or (maximum -1) in all List students

var StudentsWitHighestDebts = students .Where(s => s.ZachetDidNotPass.(some condition)) .OrderBy(s => s.Name) .ToList(); 

Suppose I have List students with objects that have a ZachetDidNotPass value of 0, 1, 2, 5, 6, 7 I need to put in the StudentsWitHighestDebts only those who have these values ​​maximum or maximum -1. Ie those with 7 and 6

Help please. Itself with the help of MSDN could not figure it out ... Can it be solved like this:

 foreach (var n in students) { if (n.ZachetDidNotPass > maxZachDidNotPass) { maxZachDidNotPass = n.ZachetDidNotPass; } if (n.ExamDidNotPass > maxExamDidNotPass) { maxExamDidNotPass = n.ExamDidNotPass; } } var StudentsWitHighestDebts = students .Where(s => s.ZachetDidNotPass == maxZachDidNotPass || s.ZachetDidNotPass == maxZachDidNotPass - 1 && s.ExamDidNotPass == maxExamDidNotPass || s.ExamDidNotPass == maxExamDidNotPass-1) .OrderBy(s => s.Name) .ToList(); 

    1 answer 1

     var arr = new[] {0, 1, 2, 5, 6, 7}; var res = from item in arr let max = arr.Max() where item == max || item == max - 1 select item; 

    Your values, I think, is easy to substitute

    • But if I have a dynamic list and there can be both 1 2 3 and 1 2 3 4 5 6 7 8, then I need to first find the max from the list through foreach, and then select the where with it. Right? - Sergey_Yysmaa
    • Did you try to run this code? Everything is already in it - DreamChild
    • I just did not understand him a little, but I tried to make my own, please look at the question - Sergey_Yysmaa
    • @Sergey_Yysmaa Well, you substitute your code in the above, is it difficult? - DreamChild
    • It seems that everything works well :). Thank! - Sergey_Yysmaa