LINQ(Language Integrated Query)是C#中的一种查询语法,它允许开发者以声明性方式编写查询,并对数据进行操作。OrderBy
是LINQ中的一个扩展方法,用于对集合中的元素进行排序。
OrderBy
方法可以用于任何实现了IEnumerable<T>
接口的集合类型。
当你需要对集合中的元素进行排序时,可以使用OrderBy
方法。例如,对一个学生列表按成绩进行排序。
在C#中,默认情况下,OrderBy
会将null值视为最小值,并将其排在最前面。如果你希望将null或空值筛选为最后一个值,可以使用ThenBy
方法结合自定义比较器来实现。
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public string Name { get; set; }
public int? Score { get; set; }
}
public class Program
{
public static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Score = 85 },
new Student { Name = "Bob", Score = null },
new Student { Name = "Charlie", Score = 78 },
new Student { Name = "David", Score = 92 }
};
var sortedStudents = students
.OrderBy(s => s.Score.HasValue)
.ThenBy(s => s.Score ?? int.MinValue)
.ToList();
foreach (var student in sortedStudents)
{
Console.WriteLine($"{student.Name}: {student.Score}");
}
}
}
OrderBy(s => s.Score.HasValue)
:首先按Score
是否有值进行排序,有值的排在前面。ThenBy(s => s.Score ?? int.MinValue)
:对于有值的Score
,按其值进行排序;对于null值,将其视为int.MinValue
,从而排在最后。通过这种方式,你可以确保null或空值在排序后被放置在集合的末尾。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云