Question

I am trying to create a method for shuffling a collection. I want it to be generic, which means it should take a specific type of collection (TCollection) of elements of type TEl. I want the method to return the same type of collection containing the same type of elements as the parameter.

This is what I have tried so far:

internal static TCollection FisherYatesShuffle<TCollection, TEl>(this TCollection objects)
    where TCollection : IEnumerable<TEl>
{
    var ret = new TEl[objects.Count()];
    ret[0] = objects.First();
    var rand = new Random();
    for (var i = 1; i < objects.Count(); i++)
    {
        var j = rand.Next(0, i);
        ret[i] = ret[j];
        ret[j] = objects.ElementAt(i);
    }

    return ret; //CS0029: Cannot implicitly convert type 'TEl[]' to 'TCollection'
  //return (TCollection)ret; //CS0030: Cannot convert type 'TEl[]' to 'TCollection'
}

Is the type of generics I am trying to use possible? If it is, how would I have to change my method?

Was it helpful?

Solution

Your best bet is to use:

where TCollection : IList<TEl>, new()

And then

var result = new TCollection();
...
    result.Add(item)
...
return result;

This will not work with arrays though - might need to special-case them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top