tags:

views:

134

answers:

3

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();
}
+3  A: 

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.

Blindy
I was aware of that, but I was looking for at method that didn't involve one or more conversions before I got what I needed.
Hauge
Well they either are of the same type or they aren't. There's no real middle ground in a staticly typed language.
Blindy
You're right again - and your comments was what prompted me to write that I probably didn't explain myself clearly enough. If you look at the code I ended up using it's probably much clearer. As you can see I was looking for a method that enable selecting a random item from a List<T>, and return it as whatever type the list contains, without converting back and forth between objects of type object.
Hauge
A: 

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));
AdaTheDev
There's no ElementAt method on List<T>, but I did use the ordinary index syntax in my code. This approach was the one I was already using, but I was going to use this a lot, so I was looking for a helper method or extension method I could use. See the original post at the top to see how I did.
Hauge
A: 

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

.Hauge

Hauge