【问题标题】:IQueryable type to an Array数组的 IQueryable 类型
【发布时间】:2014-01-29 04:35:43
【问题描述】:

我有一个像这样的动态 Linq 查询。我需要将结果集转换为数组。但我无法将 IQueryable 类型转换为数组。有什么建议吗?

我的代码:-

var query = Data.AsEnumerable()
                .AsQueryable()
                .Select("new(it[\"Country\"] as Country)", "it")
                .Take(10);

foreach (string str in query) // **getting error Unable to cast object of type 'DynamicClass1' to type 'System.String**
{

}

我这样修复它:- foreach(var str in query) 。

但我现在有另一个问题。我在查询中添加了 where 条件。现在我收到错误“类型'DataRow'中不存在属性或字段'Country'”。 以下是我的查询

 var query= Data.AsEnumerable().AsQueryable().Where("Country = @0", "London").Select("new (Country as Country)");

【问题讨论】:

  • 查询应该返回什么?解释string str 的用途。
  • AsEnumerable().AsQueryable() 似乎是个坏主意...
  • 感谢您的回复。我使用以下方法修复了它:- foreach(var str in query) 。但我现在有另一个问题。我在查询中添加了 where 条件。现在我收到错误“'DataRow' 类型中不存在属性或字段 'Country'”。以下是我的查询 var query= Data.AsEnumerable().AsQueryable().Where("Country = @0", "London").Select("new (Country as Country)");
  • 请用您尝试过的最新代码更新您的问题并说明问题所在。

标签: linq iqueryable dynamic-linq


【解决方案1】:

当您使用Dynamic LINQ 时,所有扩展都返回带有dynamic 元素的集合,因此您需要更改代码,例如像这样

foreach (dynamic str in query) 
{
    ....
}

也适用于您的情况str 是带有字段Country 的对象

更新
来自评论的问题
如果数据是DataTable,当您调用AsEnumerableAsQueryable 时,您使用的是DataRow 的集合,所以当您想按列值过滤它时,您需要像这样使用DataRow 的语法

Data.AsQueryable().Where("it[\"Country\"] = @0", "London")

或者你可以先这样选择

var query= Data.AsQueryable()
               .Select("new (it[\"Country\"] as Country)")
               .Where("Country = @0", "London")

更新2
直到你没有为字段指定类型,它可以是 Object 所以你需要像这样更改 Select 子句

....
.Select("new(Convert.ToString(it[\"Country\"]) as Country)")
....

在这种情况下,当您在Select 字段Country 之后调用Where 将是String,所以StringContains 方法

【讨论】:

  • 还有一个疑问。我已将查询更改为 var data = Data.AsEnumerable().AsQueryable().Select("new (it[\"Country\"] as Country)").Where("Country.Contains(@0)", "L"); .现在我收到错误“'对象'类型中不存在适用的方法'包含'”。有什么帮助吗?
  • 我已经看到它应该可以工作 stackoverflow.com/questions/2455659/… 。是不是因为我的数据也包含空记录?
  • 谢谢。那成功了。这是基本的,我应该在发布问题之前尝试一下。无论如何谢谢:)
猜你喜欢
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 2011-07-03
  • 2020-08-13
相关资源
最近更新 更多