Java 的 Collections.shuffle 讓人羨慕,C# 雖無內建方法,但利用 List.Insert 在隨機索引插入元素,即可以極簡代碼實現高效亂序。
Random random = new Random();
List<Content> newList = new List<Content>();
foreach (Content item in ContentList)
{
newList.Insert(random.Next(newList.Count + 1), item);
}
return newList;
OrderBy(x => random.Next()) 或手寫原地交換版 Fisher-Yates(O(n))。封裝為擴展方法:
public static void Shuffle<T>(this IList<T> list, Random rng = null)
{
rng ??= new Random();
int n = list.Count;
while (n > 1)
{
int k = rng.Next(n--);
(list[n], list[k]) = (list[k], list[n]);
}
}
原地交換,O(n) 時間、O(1) 空間,生產環境首選。