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();
}
There's no such thing as "objects not related via a base class". If nothing else you'll always have object
s. So a List<object>
will do what you want.
Ended up going with an extension method, shown as an appendix to the original post.
.Hauge
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));
精彩评论