Get Random Item from IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Get Random Item from IEnumerable

Demo Code


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

public class Main{
        public static T Random<T>(this IEnumerable<T> collection)
        {
            return collection.Random<T>(1).SingleOrDefault();
        }

        public static IEnumerable<T> Random<T>(this IEnumerable<T> collection, int count)
        {
            var rd = new Random();
            return collection.OrderBy(c => rd.Next()).Take(count);
        }
}

Related Tutorials