Finding elements of a given type in an array in C #

I have a Fleet class that contains an array of vehicles (base class). Cars in an array are subclasses of vehicles: plains, trains, and cars. The array is private, but the Fleet class must offer a method to get to vehicles of a certain type.

Sort of:

class Fleet
{
    private Vehicle[] _vehicles;

    // returns the vehicles of the specified subclass
    public ???? Get(????)
    {
        return ????
    }
}

Fleet fleet = new Fleet("fleet.def");

Trains[] trains = fleet.Get(Trains);   // looks clean but isn't possible
Plains[] plains = fleet.Get<Plains>(); // looks okay but don't know
                                       //   how to implement

(I use arrays, but really any type of collection that can be repeated is fine.)

Now, as you can see, I absolutely do not know how to implement this. I am looking for an elegant solution for the Get method, efficiency is actually not a problem. Please also name the key methods used in the solution, so I can find them in my C # books ...

Thank!

+3
3

Fleet.Get()

public IEnumerable<T> Get<T>()
{
  return _vehicles.OfType<T>();
}
+12

List<> FindAll(x => x.GetType() == typeof(Train)), Train .

+1
 public T[] Get<T>() where T : Vehicle
 {
     List<Vehicle> lstVehicles = new List<Vehicle>(_vehicles);
     return lstVehicles.FindAll(delegate(Vehicle vehicle){
         return vehicle.GetType() == typeof(T);
     }).ToArray();
 }
0

Source: https://habr.com/ru/post/1731989/


All Articles