gpt4 book ai didi

c# - 如何使用 LINQ C# 过滤列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:53 29 4
gpt4 key购买 nike

我需要过滤 List<Students>进入StudentsWitHighestDebts .

标准是只有学生在ZachetDidNotPass有最大值和maximum-1总共List<Students>包含在结果中。

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

例如,给定一个学生列表 ZachetDidNotPass0 1 2 5 6 7 .结果 StudentsWitHighestDebts应该只包含 7 and 6 的学生ZachetDidNotPass 中的值.

最佳答案

第一个选项:采取 2 个最高债务并通过 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();

第二个选项 - 按 ZachetDidNotPass 分组,按键降序对组进行排序,取前 2 个组并从组中选择学生

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

第三个选项(带最高债务和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();

关于c# - 如何使用 LINQ C# 过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29427872/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com