views:

1101

answers:

2

Hi!

I have a method where I execute a query SQL (I'm using Linq to SQL but I have to execute a classic SQL query), but I don't know from which table/Entity this query will be generated.

So, I was thinking that as I don't know from what Table the query will be generated from, I don't know the type of my IQueryable, am I right?

But I don't know how to return this IQueryable? I've tried to return <T> but it's not working.

Thanks!

A: 

You can't as you found out. Since you don't know the type there is no way to return a generic Generic (ie. List) the only other option for you with what you are doing (also anytime you want to return a subset of a strong Linq to Sql type) is to create your own type (ie.. Class or Struct) and fill a List and return that... I would guess you have some idea of the columns you are returning so it should not be too difficult.

Hope this helps Tab

Tab
+1  A: 

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.

McKAMEY