-4

I made a list of cars, the factory produces every 4 cars broken (public bool Broken;).

My code

public static void BuildCar()
{

    List<Factory> cars = new List<Factory>();

    for (int i = 1; i < 10; i++)
    {
        Factory newCars = new Cars("string", "string", "bool");
        if (i % 4 == 0)
        {
            newCars.Broken = true;
            cars.Add(newCars);
        }
        else
        {
            newCars.Broken = false;
            cars.Add(newCars);
        }
    }
}

What I did

A list of all the cars (good and broken).

What I need to do

Create a method that copies only good cars to another list.

Thx.

PavZav
  • 3
  • 4

2 Answers2

0

LINQ query:

var goodCars = cars.Where(car => !car.Broken).ToList();
JMP
  • 1,864
  • 2
  • 8
  • 16
-1

The simplest way probably:

List<Factory> goodCars = cars.FindAll(car => !car.Broken);
VillageTech
  • 1,968
  • 8
  • 18
  • 1
    'Where' is faster than 'FindAll' , where opertor returns a lazily evaluated sequence - no copying is required like 'FindAll' – KHL Feb 06 '20 at 13:34