Goal: Generic enumerated type to be the same type when returned.
Note: This works when the types are entered but I don't understand why they can't be inferred.
List<T>
then return List<T>
IOrderedEnumerable<T>
then return IOrderedEnumerable<T>
ETC
Current method (works only if all types are entered)
public static TEnumerable WithEach<TEnumerable, T>(this TEnumerable items, Action<T> action)
where TEnumerable : IEnumerable<T>
{
foreach (var item in items) action.Invoke(item);
return items;
}
Example Only
var list = new List<int>(); //TODO: Mock random values
list.WithEach(x => Console.WriteLine(x)) //Here WithEach ideally returns List<int> following orignal type List<int>
.OrderBy(x => x)
.WithEach(x => Console.WriteLine(x)); //Here WithEach ideally returns IOrderedEnumerable<int> following OrderBy
Making it work
var list = new List<int>(); //TODO: Mock random values
list.WithEach<List<int>, int>(x => Console.WriteLine(x))
.OrderBy(x => x)
.WithEach<IOrderedEnumerable<int>, int>(x => Console.WriteLine(x));
What I'm missing is why C# can't infer the types although the where
filter does make the types accurate. I understand why you either supply all or none generic types to methods so please do not point me to those answers.
Edit: If I can't infer the types; then how can I make this more elegant?