You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何在向列表插入元素时实时排序,复用现有集合无需创建新对象

方案1:最小改动直接复用现有列表(推荐)

LINQ本身是面向查询的无副作用API,默认不直接修改原集合,但你可以把排序后的查询结果直接填充到已清空的_sortedList中,不需要额外生成新的列表实例:

// system entities is IReadOnly list in another class
//_sortedList is a field in the class that i wish to reuse for sorting

_sortedList.Clear();
// 直接把排序后的惰性枚举结果添加到现有列表,不会创建新的List实例
_sortedList.AddRange(_system.entities.OrderBy(entity => entity.quantity).ThenBy(entity => entity.name));

这种方式是性能和简洁度的最优解,OrderBy返回的是惰性计算的枚举序列,AddRange遍历序列时才会执行排序逻辑,全程不会额外生成新的集合实例,完全满足复用_sortedList的需求。


方案2:插入元素时实时排序

如果你确实需要在逐个添加元素的过程中完成排序,可以自己实现一个排序插入的扩展方法,搭配遍历逻辑使用:
首先定义通用的插入排序扩展:

public static class ListExtensions
{
    public static void InsertSorted<T>(this List<T> list, T item, IComparer<T> comparer)
    {
        if (list.Count == 0)
        {
            list.Add(item);
            return;
        }
        // 二分查找合适的插入位置
        int index = list.BinarySearch(item, comparer);
        if (index < 0)
        {
            index = ~index;
        }
        list.Insert(index, item);
    }
}

之后按你的排序规则使用即可:

// 定义匹配你排序规则的比较器
var entityComparer = Comparer<Entity>.Create((a, b) =>
{
    int quantityCompare = a.quantity.CompareTo(b.quantity);
    return quantityCompare != 0 ? quantityCompare : a.name.CompareTo(b.name);
});

_sortedList.Clear();
foreach (var entity in _system.entities)
{
    _sortedList.InsertSorted(entity, entityComparer);
}

这种方案适合元素数量较大的场景,逐个插入的时间复杂度更低,避免了最后整体排序的开销。


内容的提问来源于stack exchange,提问作者WDUK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:27:03