Linq 排序对象的问题
我有一套Linq 排序对象的问题,linq,sorting,c#-4.0,Linq,Sorting,C# 4.0,我有一套汽车: var cars = new List<Car>(); cars.Add(new Car { ProductionDate = new DateTime(2011,02,02) }); cars.Add(new Car { ProductionDate = new DateTime(2011, 01, 01) }); cars.Add(new Car { ProductionDate = new DateTime(2011,04,04,04,04,04) }); ca
汽车
:
var cars = new List<Car>();
cars.Add(new Car { ProductionDate = new DateTime(2011,02,02) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 01, 01) });
cars.Add(new Car { ProductionDate = new DateTime(2011,04,04,04,04,04) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 03, 03, 3, 3, 3) });
var cars=新列表();
添加(新车{ProductionDate=new DateTime(2011,02,02)});
添加(新车{ProductionDate=newdatetime(2011,01,01)});
添加(新车{ProductionDate=新日期时间(2011,04,04,04,04)});
添加(新车{ProductionDate=newDateTime(2011,03,03,3,3,3)});
我需要按生产日期对其进行排序
结果应该是,首先我会有带有日期和时间的汽车,所以应该是带有2011、03、03、3、3、3作为生产日期的汽车,最后应该是带有2011、02、02作为生产日期的汽车。第二个应该是带有2011、04、04、04、04的汽车,第三个应该是带有2011、02、02的汽车
我可以使用foreachforeach
来实现这一点,但我相信有更好的方法来实现这一点
TimeSpan zeroTime = new TimeSpan(0);
var sortedCars = cars.OrderBy(c => c.ProductionDate.TimeOfDay.Equals(zeroTime) ? 1 : 0)
.ThenBy(c => c.ProductionDate)
.ToList();
但请记住:如果一辆车是在0:00制造的,会发生什么?日期时间由数据+时间组成。你看不到时间部分是否丢失了
如果您需要使用
可枚举.OrderBy
,那么您可以使用我的lamdba函数和LambdaComparer
,您可以在internet上找到它(如sll所建议的)我有类似的功能
var carsWithoutProductionTime = from car in cars
where car.ProductionDate.Hour == 0
orderby car.ProductionDate
select car;
var carsWithProductionTime = from car in cars
where car.ProductionDate.Hour != 0
orderby car.ProductionDate
select car;
var mergedCars = carsWithProductionTime.Union(carsWithoutProductionTime);
但它看起来很丑。我想看看更复杂的东西:)如果一辆车是0:00制造的?日期时间由数据+时间组成。你看不到时间部分是否丢失了!我没有添加它,但如果日期是0:00,我将认为它为空
var carsWithoutProductionTime = from car in cars
where car.ProductionDate.Hour == 0
orderby car.ProductionDate
select car;
var carsWithProductionTime = from car in cars
where car.ProductionDate.Hour != 0
orderby car.ProductionDate
select car;
var mergedCars = carsWithProductionTime.Union(carsWithoutProductionTime);