Search code examples
c#linqvariablesanonymous-typesdeclare

How to declare global variable for linq query that produces a sequence of anonymous types


I have a linq query that produces a sequence of anonymous types. The query is defined as:

var query = from a in Db.Table1
    join b from Db.Table2
    join...
    ...
    select new {
     a.field1, a.field2, 
     b.field1, NewName = b.field2 };

Now I would like to use this query in the following scenario:

if (x == 1)
{ query = ...
  ...rest of code_1 }
if (x == 2)
{ query = ...
  ...rest of code_2 }

'Query' from first 'if' will use different tables, joins and where statement than query from second 'if', however both will have exactly the same 'select new' statement.

In order to do that I need to declare a variable 'query' that will be visible inside 'if' statements.

When I checked 'type' of 'query' by using:

query.GetType().ToString();

it gives me:

query type = 'System.Data.Objects.ObjectQuery`1[<>f__AnonymousType7`14[System.Int32,System.String,System.String,System.String,System.Nullable`1[System.DateTime],System.Decimal,System.Nullable`1[System.DateTime],System.Decimal,System.String,System.String,System.String,System.String,System.String,System.String]]'

I can't declare a separate class as I can only write inside a method that I am writing code of. How should I declare a 'query' variable?


Solution

  • The only way I see is to define it using example like this:

    var query = Enumerable.Repeat(new
    {
        field1 = default(int),
        field2 = default(string),
        field3 = default(string),
        // other fields ...        
    }, 0).AsQueryable();
    

    where field1, field2 etc. should be your concrete property names with their actual types, in the exact order used inside the inner selects.