Sergey Oksky
Sergey Oksky

Reputation: 45

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.

Upvotes: 1

Views: 205

Answers (1)

IUnknown
IUnknown

Reputation: 22448

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();

Upvotes: 3

Related Questions