c# - 无法转换类型为 'System.Data.EnumerableRowCollection` 的对象 1[System.Int32 ]' to type ' System.IConvertible'

标签 c# linq datatable

我正在尝试使用下面的代码来存储值,但它给我错误。

int dqty=  Convert.ToInt32(from row in result.AsEnumerable()
where row.Field<string>("batch_num") == k_batch.ToString() 
select row.Field<int>("qty"));

基本上我想检索“数量”的值。

最佳答案

不管你的其他问题,你不能将列表/集合转换为整数

您需要使用 FirstOrDefault 或类似的

Enumerable.FirstOrDefault Method (IEnumerable)

Returns the first element of a sequence, or a default value if the sequence contains no elements.

示例

 int dqty = (from row in result.AsEnumerable()
              where row.Field<string>("batch_num") == k_batch.ToString() 
              select row.Field<int>("qty")).FirstOrDefault();

更新

进一步的例子

var list = new List<int>()  {23, 345, 546, 345};

var result = (
    from row in list
    where row > 23
    select row).FirstOrDefault();

Console.WriteLine(result);

输出

345

Full Demo here

关于c# - 无法转换类型为 'System.Data.EnumerableRowCollection` 的对象 1[System.Int32 ]' to type ' System.IConvertible',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074225/

相关文章:

c# - 为什么MediaElement不播放任何声音的原因

c# - Windows Phone 列表不显示数据

jsf - 将 JSF dataTable 中组件的 id 设置为数组中当前项的值

c# - 从页面外部访问应用程序状态

c# - 外汇 MT4 平台 - 使用什么类型的协议(protocol)/技术来实时更新图表?

LINQ 将字典转换为查找

c# - MVC 在不使用主键的数据库中查找行

c# - 在 MVC3 Razor 中使用 LinQ to Sql 将 Customer.customerID 输入 Advert.cutomerID

database - 如果没有加入 Google App Engine,您的数据是否必须存在于一张大表中?

excel - 使用 ClosedXML 将 Excel 工作表读入 DataTable