You could build the IQueryable<T>
inside a method and then make the method generic. If you did this then you would be able to return IQueryable<T>
directly and the C# compiler could use Type Inference to determine what T
was at compile time. This is effectively how most of the Linq operators are built except they're implemented as Extension methods.
For instance, consider the method which removes any in the list that are the default for that type:
public static IQueryable<T> FilterDefaults<T>(IQueryable<T> theSet)
{
IQueryable<T> query =
from t in theSet
where t != default(T)
select t;
return query;
}
Now when you call this in C# you can leave off the <T>
since type inference can figure out T
at compile-time to still be strongly typed:
string[] myStrs = { "ABC", null, "", "123", null, "XYZ" };
var theFilteredStrs = FilterDefaults(myStrs);
// should represent the sequence: "ABC", "", "123", "XYZ"
// note null is missing because default(string) is null
int[] myNums = { -1, 0, 3, 0, 42 };
var theFilteredNums = FilterDefaults(myNums);
// should represent the sequence: -1, 3, 42
// note 0 is missing because default(int) is 0
This is a trivial example that only uses basic types but the idea works the same for any LINQ usage (including LINQ-to-SQL) which is the power of LINQ. It doesn't care if you are ultimately going to use LINQ-to-SQL or if this is just LINQ-to-Objects.