I want to create a IEnumerable
class in C# that when get next value get it randomly from list of object
I want to get random value each time I want to get next for example I my list length is 100 and I get 1000 times value each time get random value
I create a below class but my program is hanged when create new instance from 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
{
get
{
return Current;
}
}
public FileInfo Current
{
get
{
try
{
FileInfo fi = new FileInfo(RankedList[position].MediaUrl);
return fi;
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
Using iterators with
Random
and infinite loop would be simplest solution.