Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display object in list using ID

So I made a list called cars and I am getting trouble displaying each car from list using Id. Can anyone help how to display object from list by ID?

  public List<Cars> loadCars() {

    List<string> carlines = File.ReadAllLines("Cars.txt").ToList();

    
    carlines.RemoveAt(0);

    foreach(string line in carlines)
    {
      
      string[] parts = line.Split(';');
    
      Cars cars = new Cars();
      cars.Id = parts[0];
      cars.Mark= parts[1];
      cars.Model = parts[2];
      cars.Year = parts[3];
      cars.Type = parts[4];
      cars.Engine = parts[5];
      cars.Mileage = parts[6];
      cars.Color = parts[7];
      cars.Recovery = parts[8];
      cars.Price = parts[9];
    
      allcars.Add(cars);
    }
    return allcars;
  }
  
  public void displayCar(string number) {
    loadCars();
    var carsDisplay = carlines.FirstOrDefault(c => c.Id == number);
    if(carsDisplay == null) {
      Console.WriteLine("Car not found");
    } else {
      foreach(var line in allcars) {
        Console.WriteLine(carsDisplay.ToString());
      }
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You might want to remove the foreach and just output the properties of the model object. For example:

    public List<Cars> LoadCars() {

    List<string> carlines = File.ReadAllLines("Cars.txt").ToList();

    
    carlines.RemoveAt(0);

    foreach(string line in carlines)
    {
      
      string[] parts = line.Split(';');
    
      Cars cars = new Cars();
      cars.Id = parts[0];
      cars.Mark= parts[1];
      cars.Model = parts[2];
      cars.Year = parts[3];
      cars.Type = parts[4];
      cars.Engine = parts[5];
      cars.Mileage = parts[6];
      cars.Color = parts[7];
      cars.Recovery = parts[8];
      cars.Price = parts[9];
    
      allcars.Add(cars);
    }
    return allcars;
  }
  
  public void DisplayCar(string number) {
    List<Cars> cars = LoadCars();
    var carToDisplay = cars.FirstOrDefault(c => c.Id == number);
    if(carToDisplay == null) {
      Console.WriteLine("Car not found");
    } else {
        Console.WriteLine(carToDisplay.Id);
        Console.WriteLine(carToDisplay.Mark);
        //Keep add output here
      }
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading