我有一个包含产品的列表 (List<Product>
),每个产品都有一个id、名称和价格。
如果我想要按价格降序排序该列表,是否有一行代码或扩展方法可以让我将新产品插入到正确的位置?
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public int Price {get; set;} // assume only whole integers for price
}
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({id = 5, Name="new product", Price = 17})
// Is there an short solution available that allows me to insert a new product with
// price = 17 and that will be inserted between products with price 15 and 20?
// Without repeatedly iterating over the list to find the one lower and the one higher
// than the new price and recalculate the index...
var lastIndex = products.FindLastIndex(x => x.Price >= newProduct.Price);
products.Insert(lastIndex + 1, p5);
}
编辑解决方案:我赞同 Tim Schmelter 的答案是最正确的。它不是单行代码,需要一个自定义扩展方法,但我认为没有单行解决方案可用。添加它并执行 OrderByDescending() 即可简单解决,但接下来的代码将依赖于 OrderByDescending() 语句...
.Add
后调用products = products.OrderByDescending(prd => prd.Price).ToList();
或者使用SortedList
。 - Roman Ryzhiy