How to specify parameter for extension method of general list type in C #

I am trying to create an extension method that will shuffle the contents of a common collection of lists regardless of its type, but I'm not sure what to add between <..> as a parameter. am i putting an object? or type? I would like to be able to use this in any List collection that 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);
    }
}
+5
source share
4 answers

You need to make it a general 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);
    }
}

This will allow him to work with anyone List<T>.

+11
source

You just create your own method:

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

, Fisher-Yates shuffle , :

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;
    }
}
+3

, , .

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

:

  • Create your static class to identify your extensions.
  • Create your extension method (must be static)
  • Process your data.
0
source

All Articles