Wednesday, 18 September 2013

Searching a c# List containing inherited class

Searching a c# List containing inherited class

I have created the following code just as a more simplified way to display
my problem.
I haven't ran this version through a compiler so it may have typos.
I'm am looking if there is a more condense way (or even a better way) to
search a List that contains inherited classes.
public class Engine {
public String FuelType { get; set; }
}
----------------------------------------------------------------------------
public class Wheel {
public String TyreType { get; set; }
}
----------------------------------------------------------------------------
public abstract class Car {
public abstract String Make { get; }
}
public class Ford : Car {
public override String Make {
get { return "Ford"; }
}
Public Engine Engine { get; set; }
}
public class Porche : Car {
public override String Make {
get { return "Porche"; }
}
Public Wheel Wheel { get; set; }
}
----------------------------------------------------------------------------
// CarCollection as follows:
// Ford > Engine > FuelType > "Petrol"
// Ford > Engine > FuelType > "Diesel"
// Porche > Wheel > TyreType > "Dry"
List<Car> carCollection = GetCarcollection();
What I want is a reference to the ' Ford > Engine > FuelType > "Petrol" '.
(assume the collection will only contain one)
//-- Start --
List<Ford> fordCollection = carCollection.FindAll( cc => cc.Make == "Ford" )
.Cast<Ford>().ToList();
Im not able to access the fuelType in the above so I do it in a seperate
statement below.
// This 'ford' is the reference I require
Ford ford = fordCollection.Find( fc => fc.Engine.FuelType == "Petrol" );
//-- Finish --
Although this works is it possible to combine the two above statement into
one.
The Class structure is just a simple example and the design isnt fully
relevant to my real code.

No comments:

Post a Comment