你能在 C# 中不按顺序枚举一个集合吗? [英] Can you enumerate a collection in C# out of order?

查看:15
本文介绍了你能在 C# 中不按顺序枚举一个集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 foreach 循环向后或以完全随机的顺序遍历集合?

Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?

推荐答案

正如其他答案所提到的,Reverse() 扩展方法 会让你以相反的顺序枚举一个序列.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆