Question

Is it possible to add an extension method to an IQueryable that converts it to another type of IQueryable?

I looking for something like this;

IQueryable<foo> source;
IQueryable<bar> result = source.Convert<bar>();

I have this and obviously it is not working. LOL

public static IQueryable<T1> Convert<T2>(this IQueryable<T1> source) where T1 : class
{
    // Do some stuff
}

Thanks in advance.

Was it helpful?

Solution

Surely it's already there in Select - you just need to provide the conversion. For example, to convert an IQueryable<string> to IQueryable<int> by taking the length:

IQueryable<string> source = ...;
IQueryable<int> lengths = source.Select(x => x.Length);

OTHER TIPS

You're returning the same type (IQueryable<T1>) that you have in your original queryable, so your extension method is taking an IQueryable<foo> and returning an IQueryable<foo> , where you want to return an IQueryable<bar>. Also, you define T2 as a generic type parameter, but not T1. You could change to this:

public static IQueryable<T2> Convert<T1, T2>(IQueryable<T1> source) where T1 : class
{
...
}

Then invoke like so:

IQueryable<Bar> result = source.Convert<Foo, Bar>();

But.. as Jon points out, this could be done in a Select. If the conversion between foo and bar is not so trivial, or you want to re-use it, you could define that mapping, rather than converting an IQueryable to IQueryable.

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