【问题标题】:How to find a class object in a List<T> by one or more of class fields? [duplicate]如何通过一个或多个类字段在 List<T> 中查找类对象? [复制]
【发布时间】:2020-11-09 23:30:01
【问题描述】:

我有这个代码:

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;
    }

在 Garage 类中,我需要实现 DeleteCar 方法。那么当方法调用时,用户输入全部4个字段或其中的一部分,然后List中的对象就会被定位并删除,如何实现,有什么帮助呢?

【问题讨论】:

  • 你尝试了什么?你注意到List&lt;T&gt; 上的RemoveAll(Predicate&lt;T&gt;) 方法了吗?
  • 重复假设问题是“如何通过 public 属性在列表中查找/删除项目。如果您的问题是关于您的确切样本(这通常没有意义,但是可能确实是您想要实现的目标)没有任何公共领域请edit问题澄清。所以问题可能会重新打开

标签: c# algorithm


【解决方案1】:

对于删除可以使用 RemoveAll() 方法:

https://docs.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);
}

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));
}

【讨论】:

  • 也许这个问题是另一个帖子的问题,但我应该问:可能你的代码对我有好处,但所有字段都有访问错误。如何在不将字段设置为公开的情况下授予对字段的访问权限,是否可能?
  • @rhapsodyy,你可以在Car类中实现Equals()方法。在这种情况下,所有成员都可以保持私密。我将调整原始帖子以显示如何做到这一点
猜你喜欢
  • 2021-09-12
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 2012-05-26
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
相关资源
最近更新 更多