How to select N Random Items from the List in C#

February 20, 2022 0 comments
This post is about, how to select N Random Items from any T list in C# 

 e.g. Say we have IList with total count of 1000 and we need to get 100 random items from the List. We should use following function to return N Random Items from any List in C#

public IEnumerable <T> PickRandom<T>(IEnumerable<T> list, int number)
{
    var random = new Random();
    var total = list.Count();
    var required = number;
    foreach (var item in list)
    {
        if (random.Next(total) < required)
        {
            required--;
            yield return item;
            if (required == 0)
            {
                break;
            }
        }
        total--;
    }
}

Share Share Tweet Share

0 thoughts on "How to select N Random Items from the List in C#"

LEAVE A REPLY