-2

I have this code:

class Garage
    {
        private List <Car> cars;

        public void AddCar (string carModel, string color, double speed, int yearOfIssue)
        {
            Car car = new Car (carModel, color, speed, yearOfIssue);
            cars.Add (car);
        }

        public void DeleteCar (string carModel, string color, double speed, int yearOfIssue)
        {
           
        }
    }

    class Car
    {
        public Car ()
        {
            
        }

        public Car (string carModel, string color, double speed, int yearOfIssue)
        {
            this.carModel = carModel;
            this.color = color;
            this.speed = speed;
            this.yearOfIssue = yearOfIssue;
        }

        private string carModel;
        private string color;
        private double speed;
        private int yearOfIssue;
    }

In Garage class, I need to implement the DeleteCar method. So when method is calling, user enters all 4 fields or some of them, and after that the object in the List will be located and deleted, how can this be implemented and with what help?

rhapsodyy
  • 1
  • 1
  • What have your tried? Did you notice the `RemoveAll(Predicate)` method on `List`? – Enigmativity Nov 09 '20 at 23:32
  • Duplicates assume that the question is "how to find/remove item in list by *public* property. If you question is about your exact sample (which generally makes no sense, but may indeed be what you want to achieve) that does not have any public fields please [edit] question to clarify that. So question can be possibly re-opened – Alexei Levenkov Nov 10 '20 at 01:18

1 Answers1

0

For deleting can be used RemoveAll() method:

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=netcore-3.1

public void DeleteCar (string carModel, string color, double speed, int yearOfIssue)
{
    cars.RemoveAll(c => 
        c.carModel == carModel && 
        c.color == color&& 
        c.speed == speed&& 
        c.yearOfIssue == yearOfIssue);
}

or

class Car
{
    public bool Equals(Car other)
    { 
        return other.carModel == carModel && 
             other.color == color&& 
             other.speed == speed&& 
             other.yearOfIssue == yearOfIssue;
    }
}

public void DeleteCar (string carModel, string color, double speed, int yearOfIssue)
{
    Car car = new Car (carModel, color, speed, yearOfIssue);
    cars.RemoveAll(c => c.Equals(car));
}
xtadex
  • 96
  • 1
  • 4
  • Maybe this question for anoter post but i should ask: probably your code is good for me but have access errors for all fields. How can i give access to fields without setting them to public, is it possible? – rhapsodyy Nov 09 '20 at 23:51
  • @rhapsodyy, you can implement `Equals()` method in `Car` class. In that case, all members can stay private. I will adjust original post to show how to do it – xtadex Nov 10 '20 at 23:38