在C# Linq中,当类型未知时如何初始化IQueryable或var变量,并且linq查询返回动态字段/对象

问题描述 投票:0回答:1

我有下面的示例代码,但不知道如何初始化变量。

// using any of the below at a time does not compile
var queryResults = null; // this is not possible anyways, as vars must be initialized.
// or
IQueryable queryResults = null;
// or is it something like?
IQueryable<T> queryResults = null;

// and I have an if block

if(some-condition == true) {
  queryResults = (from t1 in table select new { column1 = t1.column1 })
} else {
  queryResults = (from t2 in table2 select new { column1 = t2.column1 })
}

// and then use the queryResults below:

foreach(var item in queryResults) {
   Console.Writeline(item.column1);
}

如何声明变量,以便可以使用它来分配 if 块中的查询结果,并使用返回查询的属性(在本例中为列 1),如上面的循环所示?

c# fiddle - 接近实际代码。

c# linq iqueryable
1个回答
0
投票

我没有发现代码有任何问题。请是相同的输出

© www.soinside.com 2019 - 2024. All rights reserved.