简体   繁体   中英

How to filter List With LINQ C#

I need to filter a List<Students> into StudentsWitHighestDebts .

The criteria is that only students where ZachetDidNotPass has maximum value and maximum-1 in all List<Students> are included in the result.

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

For example, given a list of students that have ZachetDidNotPass values 0 1 2 5 6 7 . The resulting StudentsWitHighestDebts should only contain the students with 7 and 6 values in ZachetDidNotPass .

First option: take 2 highest debts and filter students by ZachetDidNotPass:

var highestDebts = students.Select(s => s.ZachetDidNotPass)
    .OrderByDescending(p => p).Take(2).ToArray();
var studentsWitHighestDebts = students
    .Where(s => highestDebts.Contains(s.ZachetDidNotPass))
    .OrderByDescending(s => s.ZachetDidNotPass).ToList();

Second option - group by ZachetDidNotPass, sort groups by key descending, take top 2 groups and select students from groups

var studentsWitHighestDebts = students.GroupBy(s => s.ZachetDidNotPass)
    .OrderByDescending(g => g.Key).Take(2)
    .SelectMany(g => g).ToList();

And third option (take students with highest debt and highestDebt - 1)

var highestDebt = students.Max(s => s.ZachetDidNotPass);

var studentsWitHighestDebts = students
    .Where(s => s.ZachetDidNotPass == highestDebt || s.ZachetDidNotPass == highestDebt - 1)
    .OrderByDescending(s => s.ZachetDidNotPass).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM