Search code examples
c#iqueryablegeneric-collections

IQueryable<T1> extension method to convert to IQueryable<T2>


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.


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);