在C#中,你可以使用LINQ来对列表进行排序。以下是一个示例代码,演示如何按价格对列表进行排序:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List products = new List()
{
new Product() { Name = "Product 1", Price = 10 },
new Product() { Name = "Product 2", Price = 5 },
new Product() { Name = "Product 3", Price = 15 },
new Product() { Name = "Product 4", Price = 8 }
};
// 使用LINQ按价格对列表进行排序
var sortedProducts = products.OrderBy(p => p.Price);
// 打印排序后的列表
foreach (var product in sortedProducts)
{
Console.WriteLine(product.Name + " - " + product.Price);
}
}
}
class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
在上面的示例中,我们创建了一个Product
类来表示产品,包含名称和价格属性。然后,我们创建了一个List
对象来存储产品列表。
使用LINQ的OrderBy
方法,我们可以按产品价格对列表进行排序。在这个例子中,我们使用lambda表达式p => p.Price
来指定按价格排序。
最后,我们通过迭代排序后的列表来打印排序结果。
运行上述代码,输出将会是:
Product 2 - 5
Product 4 - 8
Product 1 - 10
Product 3 - 15
这是按照价格排序后的列表。