简体   繁体   中英

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

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> .

您只需将自己的方法设为通用的:

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM