C# 如何打印已排序的列表?
我正试图按价格范围对一系列汽车进行分类。目前我还不确定我是否已经用IComparable对它进行了正确的排序,我也不知道在排序后如何打印列表,我只能按照声明的顺序打印它们C# 如何打印已排序的列表?,c#,C#,我正试图按价格范围对一系列汽车进行分类。目前我还不确定我是否已经用IComparable对它进行了正确的排序,我也不知道在排序后如何打印列表,我只能按照声明的顺序打印它们 using System; using System.Collections.Generic; namespace Interface1 { class Program { class Car : IComparable<Car> { pub
using System;
using System.Collections.Generic;
namespace Interface1
{
class Program
{
class Car : IComparable<Car>
{
public string Make { get; set; }
public string Model { get; set; }
public double Price { get; set; }
public int CompareTo(Car car)
{
return this.Price.CompareTo(car.Price);
}
static void Main(string[] args)
{
List<Car> cars = new List<Car>()
{
new Car(){Make = "Skoda", Model = "Fabia", Price = 50000},
new Car(){Make = "Skoda", Model = "Octavia", Price = 60000},
new Car(){Make = "Nissan", Model = "Juke", Price = 45000 }
};
foreach (var car in cars)
Console.WriteLine(car.Price);
}
}
}
}
使用系统;
使用System.Collections.Generic;
名称空间接口1
{
班级计划
{
汽车等级:I可比
{
公共字符串Make{get;set;}
公共字符串模型{get;set;}
公共双价{get;set;}
公共内部比较(汽车)
{
返回此.Price.CompareTo(car.Price);
}
静态void Main(字符串[]参数)
{
列出车辆=新列表()
{
新车(){Make=“Skoda”,Model=“Fabia”,Price=50000},
新车(){Make=“Skoda”,Model=“Octavia”,Price=60000},
新车(){Make=“Nissan”,Model=“Juke”,Price=45000}
};
foreach(车辆中的var车辆)
控制台写入线(汽车价格);
}
}
}
}
我的分类正确吗?如何正确打印?将此行更改为正确打印
foreach (var car in cars.OrderBy(x => x.Price))
Console.WriteLine(car.Price);
您也可以在
OrderBy
函数中添加不同的比较器。列表的排序位置?这是否回答了您的问题?你可能想调查一下这个问题。您所使用的只是一个简单的列表,它不会自动进行任何排序,即使您已经正确地实现了IComparable
。