您可以枚举在C#集合失灵? [英] Can you enumerate a collection in C# out of order?
本文介绍了您可以枚举在C#集合失灵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有使用的foreach
遍历集合向后或在一个完全随机的顺序进行迭代的方式?
Is there a way to use a foreach
loop to iterate through a collection backwards or in a completely random order?
推荐答案
至于其他的答案提到的 反向()
扩展方法会让你列举顺序相反的顺序
As other answers mention, the Reverse()
extension method will let you enumerate a sequence in reverse order.
下面是一个随机的枚举扩展方法:。
Here's a random enumeration extension method:
public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T> sequence)
{
Random random = new Random();
List<T> copy = sequence.ToList();
while (copy.Count > 0)
{
int index = random.Next(copy.Count);
yield return copy[index];
copy.RemoveAt(index);
}
}
您用法是:
foreach (int n in Enumerable.Range(1, 10).OrderRandomly())
Console.WriteLine(n);
这篇关于您可以枚举在C#集合失灵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文