我有一个ObservableCollection与对象。我想随机化集合的顺序。我该怎么做呢?
您可以使用扩展方法来做到这一点。可以将该类添加到项目中,以提供集合的扩展方法。这是一个简单的洗牌
public static class ShuffleExtension
{
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
使用,调用yourcollection.Shuffle()