0

我有一个列表,其中 T 有一个属性 CoverImage。我想以随机顺序访问列表中的所有项目并从服务器加载适当的图像。我对从服务器加载数据不感兴趣,我只想知道如何以随机方式访问该列表中的所有元素并且只访问一次?

4

4 回答 4

4
Random rnd = new Random();
foreach(var elem in list.OrderBy(x => rnd.Next()))
{

}
于 2013-01-10T22:31:38.217 回答
2

合适的术语是shuffling。洗牌是将集合/序列重新排序为随机顺序的概念。

这样做的方法有很多,对性能的影响各不相同。F isher–Yates shuffle是一个不错的选择

伪代码:

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]
于 2013-01-10T22:32:36.847 回答
0
Random r = new Random();
List<T> myListRnd = new List<T>();

int p = 0;
while (myList.Count > 0)
{
    p = r.Next(myList.Count + 1)
    myListRnd.Add(myList[p]);
    myList.RemoveAt[p];
}
于 2013-01-10T22:41:55.533 回答
0

如果您有兴趣编写自己的扩展方法,它可能如下所示:

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable, Random random)
{
    List<T> itemList = new List<T>(enumerable);

    for (int i = 0; i < itemList.Count; ++i)
    {
        int randomIndex = random.Next(itemList.Count);
        if (randomIndex != i)
        {
            T temp = itemList[i];
            itemList[i] = itemList[randomIndex];
            itemList[randomIndex] = temp;
        }
    }

    return itemList;
}
于 2013-01-10T23:02:11.830 回答