How to cast while Sorting?

你说的曾经没有我的故事 提交于 2020-01-07 02:48:10

问题


I have classes Vehicle and class:Car is inherited from class:Vehicle as in below. I have a List which I want to sort using LINQ based on a property of Car class (not of vehicle parent class).

class vehicle
{
    public String Name {get; set; }
}

class Car:Vehicle
{
    public String ModelName {get; set; }
}

List<Vehicle> vehicleList=new List<Vehicle>();

Car c1 = new Car();
vechicleList.Add(c1); //s note that i am adding **Car** objects

Car c2 = new Car();
vechicleList.Add(c2);
// added 10 such Car objects

Then I want to Sort vehicleList based on CarModel (which is a property of Car, not of Parent class)

I tried the below one but it does not work.

vehicleList.OrderBy(c => (Car)c.ModelName)

Any help on how to do this?


回答1:


The most readable code that does what you want is

vehicleList.Cast<Car>().OrderBy(c => c.ModelName);

while of course you could also fix the parens and write the same as

vehicleList.OrderBy(c => ((Car)c).ModelName);

That said, both of the above will blow up if there is any Vehicle in your list that is not a Car. And if that can't happen, then why isn't that a List<Car> in the first place?




回答2:


You have to decide what you want to have:

A list of Car instances or a list of Vehicle instances.

If you want to have a list of Vehicle instances you can't order by properties of Car, because in a list of Vehicles there also could be a Bus or a Bicycle.
Doing what you currently try (casting to Car) will possibly throw an exception at runtime.

Having said that, if you insist on doing it, you have to be aware of two things:

  1. You need to fix your cast: vehicleList.OrderBy(c => ((Car)c).ModelName)
  2. You need to be aware that OrderBy doesn't perform an in-place sort. vehicleList will still be in its original ordering. If you want to have the ordered result in vehicleList, you need to assign the result of OrderBy to it:

    vehicleList = vehicleList.OrderBy(c => ((Car)c).ModelName).ToList();
    



回答3:


You have to cast c into a Car, not c.ModelName.

Try :

vehicleList.OrderBy(c => ((Car)c).ModelName)



回答4:


try use:

vehicleList.OfType<Car>().OrderBy(c=>c.ModelName)

note: this returns only cars from yours list




回答5:


vehicleList.OfType<Car>().OrderBy(c=>c.ModelName)



回答6:


Try this:

vehicleList.OrderBy(c=>((Car)c).ModelName)

but beware it will blow up if an item is not actually a car!

A way around that would be:

vehicleList.OrderBy<Vehicle, string>(c=>
{
    Car car = c as Car;
    if (car != null)
        return car.ModelName
    else
        return "";
}

But if there were 'non-cars' there position would be determined by the empty string in relation to other items in the list.



来源:https://stackoverflow.com/questions/14938738/how-to-cast-while-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!