Home > Mobile >  How to display object in list using ID
How to display object in list using ID

Time:05-06

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

CodePudding user response:

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
      }
    }
  }
  •  Tags:  
  • c#
  • Related