ienumerable - C# - Create Enumeraor that Get Values Randomly -
i want create ienumerable
class in c# when next value randomly list of object
i want random value each time want next example list length 100 , 1000 times value each time random value
i create below class program hanged when create new instance class
public class myenumerable:system.collections.ienumerable { public int regionid { get; set; } list<medium> rankedlist; mediaenumerator pe; public mylist(int regionid) { regionid = regionid; rankedlist = showvideo.getranklist(regionid); pe = new mediaenumerator(rankedlist); } public system.collections.ienumerator getenumerator() { return (ienumerator)(pe); } } public class mediaenumerator : ienumerator { list<medium> rankedlist; int position = -1; public mediaenumerator(list<medium> list) { rankedlist = list; } random rnd = new random(); public bool movenext() { position = rnd.next(rankedlist.count); return true; } public void reset() { position = -1; } object ienumerator.current { { return current; } } public fileinfo current { { try { fileinfo fi = new fileinfo(rankedlist[position].mediaurl); return fi; } catch (indexoutofrangeexception) { throw new invalidoperationexception(); } } } }
using iterators random
, infinite loop simplest solution.
public ienumerable<t> getrandomelements<t>(t[] elements) { random rand = new random(); while(true) { int index = rand.next(0, elements.length); yield return elements[index]; } }
Comments
Post a Comment