Hauge
Hauge

Reputation: 1719

Select random from generic lists with different <T>

I'm looking for the best way to make it possible to get a random element from a List where the T's will be objects of different types that is not related via a base class.

I've been loooking at creating an extension method to List, or a helper method that recieves a List, but I haven't been able to get it together. Each time I've run into problems handling a T that I don't know what is.

Is it possible to do this without making an interface or a base class? Because I can't see any meaningful way of implementing a base class or interface for the different T's.

Regards Jesper Hauge


After some more reading about generic methods I managed to write some code myself. This is my solution:

public static class ListExt
{
    public static T RandomItem<T>(this List<T> list)
    {
        if (list.Count == 0)
            return default(T);
        if (list.Count == 1)
            return list[0];
        Random rnd = new Random(DateTime.Now.Millisecond);
        return list[(rnd.Next(0, list.Count))];
    }
}

It's an extension method that enables selecting a random item from any List with the following code:

private Picture SelectTopPic()
{
    List<Picture> pictures = GetPictureList();
    return pictures.RandomItem();
}

Upvotes: 5

Views: 2318

Answers (3)

Hauge
Hauge

Reputation: 1719

Ended up going with an extension method, shown as an appendix to the original post.

.Hauge

Upvotes: 1

AdaTheDev
AdaTheDev

Reputation: 147264

To get a random element from a List, you could just use the .ElementAt method, passing a randomly generated index of the element to retrieve.

There is actually an example of how to retrieve a random element from the list, in that MSDN link above:

Random random = new Random(DateTime.Now.Millisecond);
object randomItem = yourList.ElementAt(random.Next(0, yourList.Length));

Upvotes: 0

Blindy
Blindy

Reputation: 67376

There's no such thing as "objects not related via a base class". If nothing else you'll always have objects. So a List<object> will do what you want.

Upvotes: 3

Related Questions