Generic Extension Method on IQueryable <T>

I wrote an extension method for IQueryable that returns the same type of IQueryable, just a little filtered. So to speak:

public static IEnumerable<T> Foo<T>(this IEnumerable<T> source, int? howmany = null) { if (howmany.HasValue) return source.Take(howmany.Value); return source; } 

calling the above method is as simple as someLinqResult.Foo(2)

I need another method that will return an instance of another general class, but with a different base class (not the same as the original T above). So, here is the code, suppose that this method should return a list of the given type (except for the input type that has IQueryable!), But the same length [the actual problem is converting the results of the NHibernate query, but this is not matter):

 public static List<TTarget> Bar<TTarget,TSource>(this IEnumerable<TSource> source) { return new List<TTarget>(source.Count()); } 

now, given that strLinqResult is an IQueryable<string> , I need to call it strLinqResult.Bar<int,string>(); .

Point I need to pass both types, even if the first is already known , as I call the method on an already defined IQuerable .

Since this was enough to call Foo(2) and not Foo<string>(2) , I thought that the compiler could automatically "pass / guess" the type.

So why do I need to call the second method Bar<int,string>(); , not just Bar<int>() ?


actual code:

  public static ListResponse<TResponse> BuildListResponse<T,TResponse>(this IQueryable<T> iq, ListRequest request) where TResponse: new() { var result = iq.ApplyListRequestParams(request).ToList().ConvertAll(x => x.TranslateTo<TResponse>()); var tcount = iq.Count(); return new ListResponse<TResponse> { Items = result, _TotalCount = tcount, _PageNumber = request._PageNumber ?? 1, }; } 

ApplyListRequestParams is a kind of Foo method from the sample code - it just applies the pagination and ordering options available in the ListRequest object.

Items is a public List<T> Items in class ListResponse<T> .

TranslateTo is a method from ServiceStack.

The aforementioned method, called IQueryable<T> , returned by NHibernate (T is the domain model), accepts query parameters (ordering, pagination), applies them, and then converts the list of results from DomainModel to a DTO object of type TResponse . Then this list is wrapped in a common response class (general, so it is reused for many types of DTO)

+6
source share
1 answer

If I understand your problem correctly, you are trying to enter as few parameters as possible. It is simply not possible. This is all or not, where he can figure it all out.

The only problem with defining some is that you can introduce a similar method with a parameter of type 1 less and now abort the implementation.

But what chance could you share your original problem? Can you let the compiler figure it out in some other way?

+3
source

Source: https://habr.com/ru/post/947415/


All Articles