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();
}