使用 orderby 配合 count() 或 length 属性即可实现。针对引用类型集合,调用 list<t>.orderby(x => x.collectionproperty.count())</t>;针对数组,使用 x => x.arrayproperty.length。此操作会返回一个新的已排序序列,不修改原列表。

如何按嵌套对象中的字符串数组长度降序排列?
通过指定 OrderByDescending 并访问数组的 Length 属性来完成。假设数据模型包含一个名为 Tags 的字符串数组字段,直接对该字段应用长度比较逻辑即可得到结果。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item
{
public string Name { get; set; }
public string[] Tags { get; set; }
}
class Program
{
static void Main()
{
var items = new List<Item>
{
new Item { Name = "A", Tags = new[] { "x" } },
new Item { Name = "B", Tags = new[] { "y", "z", "w" } },
new Item { Name = "C", Tags = new[] { "m", "n" } }
};
var sorted = items.OrderByDescending(i => i.Tags.Length).ToList();
foreach (var item in sorted)
{
Console.WriteLine($"{item.Name}: {item.Tags.Length}");
}
}
}
如果集合属性为 null 会发生什么?
当集合属性为 null 时,访问其 Count 或 Length 会抛出 NullReferenceException。必须在排序前处理空值,例如使用条件运算符提供默认值 0,确保排序过程安全执行。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item
{
public string Name { get; set; }
public string[] Tags { get; set; }
}
class Program
{
static void Main()
{
var items = new List<Item>
{
new Item { Name = "A", Tags = null },
new Item { Name = "B", Tags = new[] { "y", "z", "w" } },
new Item { Name = "C", Tags = new[] { "m", "n" } }
};
// 使用 ?? 0 处理 null 情况,null 将被视为长度为 0
var sorted = items.OrderByDescending(i => (i.Tags?.Length ?? 0)).ToList();
foreach (var item in sorted)
{
Console.WriteLine($"{item.Name}: {(item.Tags == null ? 0 : item.Tags.Length)}");
}
}
}


















