Reputation: 504
I have the following class with the following extension method:
public static class CollectionsExtensions
{
public static List<List<T>> Split<T>(this List<T> collection, int size)
{
if (size == 0)
throw new ArgumentException();
var chunks = new List<List<T>>();
var chunkCount = collection.Count / size;
if (collection.Count % size > 0)
chunkCount++;
for (var i = 0; i < chunkCount; i++)
chunks.Add(collection.Skip(i * size).Take(size).ToList());
return chunks;
}
}
I use a code analyzer which helps pointing out code smells and potential flaws, and for this one I have a suggestion to switch the return type of the method to be of generic type. I've tried changing the signature of the method to be something like this:
public static List<U<T>> Split<U,T>(this U<T> collection, int size) where U : IEnumerable<T>
But unfortunately it's not working, so, is there a proper way to define a class with a method that can return a List of U collections of type T ?
Upvotes: 1
Views: 87
Reputation: 62488
When you are saying this:
where U : IEnumerable<T>
That means that U
will be a List<T>
or some type which is inheriting from IEnumerable<T>
, so that means your method's return type can be List<U>
in that case, which will be the same like List<IEnumerable<T>>
or List<List<T>>
.
At the time of using the method the compiler will resolve the type parameters U
to inject IEnumerable<T>
where T
will be the type provided.
Upvotes: 4
Reputation: 1730
You could write it like that:
public static List<U> Split<U, T>(this U collection, int size) where U : IEnumerable<T>
Upvotes: 2