使用 linq 的 orderby 方法配合 lambda 表达式,可以按对象的名称属性对 list 进行排序。只需调用 .orderby(x => x.name) 即可返回一个按名称升序排列的新序列。

如何获取按名称降序排列的结果?
若需降序排列,应使用 OrderByDescending 方法。该方法同样接受 Lambda 表达式作为排序依据,直接返回按指定字段降序排列的新序列。

如果对象名称为 null 会怎样?
当对象名称属性为 null 时,OrderBy 会将这些元素排在最前面。这是因为在 C# 中,null 被视为小于任何非空字符串值。
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
var people = new List<person>
{
new Person { Name = "Charlie" },
new Person { Name = "Alice" },
new Person { Name = null },
new Person { Name = "Bob" }
};
var sorted = people.OrderBy(p => p.Name).ToList();
foreach (var p in sorted)
{
Console.WriteLine(p.Name ?? "null");
}
}
}</person>











