Get random item from an ICollection - CSharp System.Collections

CSharp examples for System.Collections:ICollection

Description

Get random item from an ICollection

Demo Code


using System.Text;
using System.Collections.Generic;
using System.Collections;
using System;//from  www .j  a  v  a  2  s. c o  m

public class Main{
    /// <summary>
      /// Get random item from an ICollection  
      /// </summary>
      /// <param name="collection"></param>
      /// <returns>returns null if the collection is empty</returns>
      public static T RandomItem<T>(ICollection<T> collection) {
         int index = r.Next(0, collection.Count);
         IEnumerator<T> en = collection.GetEnumerator();
         for (int i = 0; i <= index; i++)
            en.MoveNext();
         return en.Current;
      }
}

Related Tutorials