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

如何在C#已按价格降序的List中插入新Product至正确位置?

问题:向已按Price降序排序的List中插入新元素的简便方案

我有一个存储Product对象的List<Product>集合,Product包含Id、Name和Price属性。该列表已按Price降序排序,请问是否存在单行代码或扩展方法,能够将新的Product对象插入到列表的正确位置?

public class Product
{
   public int Id { get; set; }
   public string Name { get; set; }
   public int Price { get; set; }   // 假设价格仅为整数
}

public class Main
{
   List<Product> products = new();
   products.Add(new Product { Id = 1, Name = "Product1", Price = 10 });
   products.Add(new Product { Id = 2, Name = "Product2", Price = 15 });
   products.Add(new Product { Id = 3, Name = "Product3", Price = 11 });
   products.Add(new Product { Id = 4, Name = "Product4", Price = 20 }); 

   products = products.OrderByDescending(prd => prd.Price).ToList();

   var newProduct = new Product { Id = 5, Name = "new product", Price = 17 };

   // 能否找到简便方案,将价格为17的新产品插入到价格15和20的产品之间?
   // 无需反复遍历列表查找价格高低项并重新计算索引...
   var lastIndex = products.FindLastIndex(x => x.Price >= newProduct.Price);
   products.Insert(lastIndex + 1, newProduct);     
}

解决方案编辑:我认为Tim Schmelter的答案最准确,它需要自定义扩展方法,并非单行代码,但目前不存在单行解决方案。添加新元素后重新调用OrderByDescending()虽简单,但后续代码需依赖该排序语句。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:35:54