我正在尝试显示带有和不带有LINQ的随机列表的内容。
正常列表输出示例: 普拉达(Prada),阿迪达斯(Adidas),李维斯(Levis),马球(Polo),猜(Guess)
随机化列表输出示例: 马球,阿迪达斯,普拉达,盖斯,李维斯
List<string> clothingBrands = new List<string>()
{ "Prada","Adidas","Levis", "Polo","Gucci",
"Calvin Klein","Aeropostale","Tommy Hilfiger","Puma","American Eagle",
"Lacoste","Hollister","Guess","Under Armour","Old Navy",
"Banana Republic","Hugo Boss", "Diesel","Coach","AND1"};
private static void RandomzeClothingBrands(List<string> clothingBrands)
{
Random rnd = new Random();
int i = 1;
foreach (string item in clothingBrands)
{
Console.WriteLine($"{i}.{item}");
}
}
如何完成每次随机打印的列表内容的打印?
答案 0 :(得分:0)
要将列表随机化,您可以只使用random和OrderBy
注意 :有 个更可靠的方法来随机排列列表
private static Random _rand = new Random();
...
foreach (string item in clothingBrands.OrderBy(x => _rand.Next()))
{
Console.WriteLine($"{i}.{item}");
}