如何随机订购IEnumerable<&gt ;? [英] How can I randomly ordering an IEnumerable<>?

查看:78
本文介绍了如何随机订购IEnumerable<&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个IEnumerable:

I have this IEnumerable :

IEnumerable<MyObject>

,我需要随机订购MyObject的列表.我需要转换为ArrayList吗?

and I need to order the list of the MyObject randomly. Do I need to cast into an ArrayList?

或者我可以直接做到吗?谢谢

Or I can do it directly? Thanks

编辑

这是我实际的随机顺序函数:

this is my actual random order function :

IList<ArchiePacchettoOfferta> list = new List<ArchiePacchettoOfferta>(m_oEnum);
for (int i = 0; i < list.Count; ++i)
{
    HttpContext.Current.Response.Write(list[i].Titolo + "<br />");
}

Random rnd = new Random();
for (int i = 0; i < list.Count; ++i)
{
    int swapIndex = rnd.Next(i + 1);
    ArchiePacchettoOfferta tmp = list[i];
    list[i] = list[swapIndex];
    list[swapIndex] = tmp;
}

for (int i = 0; i < list.Count; ++i)
{
    HttpContext.Current.Response.Write(list[i].Titolo + "<br />");
}

它每次都以相同的方式对列表进行排序:(

it orders the list in the same way every time :(

推荐答案

枚举器仅允许迭代"访问.因此,不可能随机或以排序方式访问元素.您必须阅读枚举值,并将其(临时)存储在另一个列表中,您可以针对该列表应用(随机)排序算法.

Enumerators allow "iterated" access only. Thus, there is no possibility to access the elements randomly or in a sorted way. You have to read the enumerated values and (temporarily) store them in another list for which you can apply your (random) sorting algorithm.

示例:

List<MyObject> list = new List<MyObject>( my_enumerable );
Random rnd = new Random(/* Eventually provide some random seed here. */);
for (int i = list.Count - 1; i > 0; --i)
{
    int j = rnd.Next(i + 1);
    MyObject tmp = list[i];
    list[i] = list[j];
    list[j] = tmp;
}
my_enumerable = list;

(我尚未测试示例代码.)

(I have not tested the example code.)

这篇关于如何随机订购IEnumerable&lt;&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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