1

In c# have a list of objects. For example a list of "cars" with attribute "color". Now I want to order randomly all cars with attribute "green" for example.

Car c01 = new Car("green","HONDA");
Car c02 = new Car("blue","BMW");
Car c03 = new Car("green","NISSAN");
Car c04 = new Car("blue","VW");
Car c05 = new Car("red","MERCEDES");
Car c06 = new Car("green","BMW");

List<CarAcceleration> Cars = new List<CarAcceleration>();
Cars.Add (c01);
Cars.Add (c02);
Cars.Add (c03);
Cars.Add (c04);
Cars.Add (c05);
Cars.Add (c06);

My idea would be to first write all green cars to a second list, reorder it and then somehow overwrite the elements in the first big list. Is there maybe a better solution? Thanks


Sorry if this has been misleading: I still want to keep the rest of the list in right order. For example this arrangement would be a solution:

Car c06 = new Car("green","BMW");
Car c02 = new Car("blue","BMW");
Car c01 = new Car("green","HONDA");
Car c04 = new Car("blue","VW");
Car c05 = new Car("red","MERCEDES");
Car c03 = new Car("green","NISSAN");
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • are you randomly reordering the green cars index only or will other car colours be overwritten by green cars making duplicates in the original list?? – NotARobot Sep 28 '17 at 22:29
  • Have you checked this? https://stackoverflow.com/questions/273313/randomize-a-listt – Marcelo Myara Sep 28 '17 at 22:34

1 Answers1

1

This works:

var rnd = new Random();
var shuffledGreen =
    Cars
        .Where(c => c.Color == "green")
        .OrderBy(c => rnd.Next())
        .ToArray();

for (int i = 0, j = 0; i <= Cars.Count() - 1; i++)
{
    if (Cars[i].Color == "green")
    {
        Cars[i] = shuffledGreen[j++];
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172