Grant
Grant

Reputation: 11356

How to specify parameter for generic list type extension method in c#

I am trying to make an extension method that will shuffle the contents of a generic list collection regardless of its type however im not sure what to put in between the <..> as the parameter. do i put object? or Type? I would like to be able to use this on any List collection i have.

Thanks!

public static void Shuffle(this List<???????> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        object o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}

Upvotes: 5

Views: 8208

Answers (4)

LukeH
LukeH

Reputation: 269348

Slightly off-topic, but a Fisher-Yates shuffle will have less bias and better performance than your method:

public static void ShuffleInPlace<T>(this IList<T> source)
{
    if (source == null) throw new ArgumentNullException("source");

    var rng = new Random();

    for (int i = 0; i < source.Count - 1; i++)
    {
        int j = rng.Next(i, source.Count);

        T temp = source[j];
        source[j] = source[i];
        source[i] = temp;
    }
}

Upvotes: 3

Diego Mendes
Diego Mendes

Reputation: 11341

I Think this solution faster to process, because you will get your itens randomly and your collection position will be preserved to future use.

namespace MyNamespace
{
    public static class MyExtensions
    {
        public static T GetRandom<T>(this List<T> source)
        {
            Random rnd = new Random();
            int index = rnd.Next(0, source.Count);
            T o = source[index];
            return o;
        }
    }
}

Steps:

  1. Create your Static Class to Identify your extensions
  2. Create you Extension Method (must be static)
  3. Process your data.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

You need to make it a generic method:

public static void Shuffle<T>(this List<T> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        T o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}

That will allow it to work with any List<T>.

Upvotes: 11

Pavel Minaev
Pavel Minaev

Reputation: 101565

You just make your own method generic:

public static void Shuffle<T>(this List<T> source)

Upvotes: 4

Related Questions