Boernie Boernie - 1 year ago 94
C# Question

c# randomize List <action>

I know that a version of this question prob gets asked quite frequently, but i looked into the forums for the last days and tried to implement the Fisher-Yates shuffle, but i didn´t manage to do it since i always get an error since it doesn´t take Shuffle as a function and gives this error: Entscheidungsfragen.Shuffle(this System.Collections.Generic.IList)': Extension methods must be defined in a non-generic static class.

private static System.Random rng = new System.Random();

public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}

private static void CreateList(string[] args)
{
var scenes =new List<Action>(szene1, szene2);
scenes.Shuffle ();
foreach (Action sce in scenes)
sce ();
}


I´d really appreciate if someone could help me, since i´m just lost cause i tried everything i found.

Answer Source

The error says it. Move your extension method Shuffle into a non-generic static class like this:

public static class ListExtensions
{
    private static System.Random rng = new System.Random();

    public static void Shuffle<T>(this IList<T> list)  
    {  
        int n = list.Count;  
        while (n > 1) {  
            n--;  
            int k = rng.Next(n + 1);  
            T value = list[k];  
            list[k] = list[n];  
            list[n] = value;  
        }  
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download