在c#中有一个对象列表。例如,具有属性“颜色”的“汽车”列表。现在我想随机订购所有属性为“绿色”的汽车。
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);
我的想法是首先将所有绿色汽车写入第二个列表,重新排序,然后以某种方式覆盖第一个大列表中的元素。可能有更好的解决方案吗?感谢
很抱歉,如果这是误导性的:我仍然希望保持列表的其余部分正确。例如,这种安排将是一个解决方案:
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");
答案 0 :(得分:1)
这有效:
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++];
}
}