i'm currently writing an application with a parent class named 'Vehicle' and two children classes named 'Car' and 'Truck'. My problem is that I would like to search through the full list of Vehicles and return only each car, or each truck depending on what object is placed into a method. Right now I have had to write a method for ach search term such as below:
public string searchCarsByName(string nameString)
{
string carNames = "";
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
carNames += car.ToString();
}
}
if (carNames == "")
{
return "No cars found";
}
else
{
return carNames;
}
}
public string searchTrucksByName(string nameString)
{
string truckNames = "";
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
truckNames += name.ToString();
}
}
if (truckNames == "")
{
return "No vehicle found";
}
else
{
return truckNames;
}
}
My only problem is that the names isn't the only way I would like to search, so for each search I am going to perform then I will have to write two methods. What i'm looking for is a way to pass in an Object to the method, and then dependent on the object it will append the necessary details to the string such as below:
public string searchVehiclesByName(Vehicle nameString)
{
string vehicleNames = "";
if(Vehicle.Type == car)
{
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
vehicleNames += car.ToString();
}
}
}
else
{
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
vehicleNames += truck.ToString();
}
}
}
if (vehicleNames == "")
{
return "No vehicles found";
}
else
{
return vehicleNames;
}
}
}
Essentially what I need is a way to pass in a parent object and check if an object is of a certain child type before creating the resultant string, rather than having to pass each individual type of child object into a method to get the results I want.
Thank you in advance.