I have a collection of Car
:
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) });
I need to sort it by ProductionDate
.
Result should be that at first I will have cars with date with time, so it should be car with 2011, 03, 03, 3, 3, 3 as production date, and at the end should be car with 2011, 02, 02 as production date. Second should b开发者_StackOverflowe car with 2011, 04, 04, 04, 04, 04, and the third with 2011, 02, 02.
I can do it by using foreach
but I believe that there is nicer way to do it.
cars.Sort((p, q) => {
var tm1 = p.ProductionDate.TimeOfDay;
var tm2 = q.ProductionDate.TimeOfDay;
if (tm1.Ticks == 0) {
if (tm2.Ticks == 0) {
return p.ProductionDate.CompareTo(q.ProductionDate);
}
return 1;
} else if (tm2.Ticks == 0) {
return -1;
} else {
return p.ProductionDate.CompareTo(q.ProductionDate);
}
});
But remember: what happens if a car is built at 0:00? A DateTime is made of a Data+Time. You can't see if the Time part is missing!
I'll add that if you need to use the Enumerable.OrderBy
, then you can use my lamdba function with the LambdaComparer
that you can find around the internet (as suggested by sll)
TimeSpan zeroTime = new TimeSpan(0);
var sortedCars = cars.OrderBy(c => c.ProductionDate.TimeOfDay.Equals(zeroTime) ? 1 : 0)
.ThenBy(c => c.ProductionDate)
.ToList();
I have something like that
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);
but It looks ugly. I would like to see something more sophisticated :)
精彩评论