如何为生成一系列匿名类型的 linq 查询声明全局变量

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

我有一个生成一系列匿名类型的 linq 查询。查询定义为:

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

现在我想在以下场景中使用这个查询:

if (x == 1)
{ query = ...
  ...rest of code_1 }
if (x == 2)
{ query = ...
  ...rest of code_2 }
第一个 'if' 中的

'Query' 将使用与第二个 'if' 中的查询不同的表、连接和 where 语句,但是两者将具有完全相同的 'select new' 语句。

为此,我需要声明一个变量 'query',它将在 'if' 语句中可见。

当我使用 'query' 检查 'type' 时:

query.GetType().ToString();

它给了我:

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]]'

我不能声明一个单独的 class 因为我只能在我正在编写代码的方法中写入。 我应该如何声明一个 'query' 变量?

我看到的唯一方法是使用 example 来定义它,如下所示:

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

其中 field1field2 等应该是您的具体 属性 名称及其实际类型,按照内部选择中使用的确切顺序。

作为此解决方案的延续,我想询问使用动态 'where' 语句的可能性。在搜索这个时,我被多次重定向到基于 PredicateBuilder class 的解决方案,但这需要方法语法而不是查询语法。我需要将我的查询转换为 lambda 还是有其他方法可以完成此操作?

我的附加 'where'(因为我已经有一些 'where' 条件)语句应该类似于:

where
( a.field1 = a[0] and b.field1 = b[0] ) ||
( a.field1 = a[1] and b.field2 = b[1] ) ||
( a.field1 = a[2] and b.field2 = b[2] ) ||
....
( a.field1 = a[a.Length] and b.field2 = b[b.Length] )