【问题标题】:LINQ Query in DataTable数据表中的 LINQ 查询
【发布时间】:2012-06-27 10:08:16
【问题描述】:

我有一个名为dtDataTable。它有两个名为 atype_codemodule 的列。 现在我需要根据特定的atype_code 查询一个模块。

这是我写的代码,但不能正常工作。

DataTable dt = GetATypeCodeList();
var accType = (from myAccType in dt.AsEnumerable()
           where myAccType.Field<string>("atype_code") == aTypeCode.Trim()
           select myAccType.Field<string>("module"));

acctypeSystem.Data.EnumerableRowCollection&lt;System.String&gt;

【问题讨论】:

  • accType 显示 {System.Data.EnumerableRowCollection}我怎样才能从中取出字符串???谢谢

标签: asp.net linq datatable


【解决方案1】:

既然你说你

需要根据具体的atype_code查询某个模块

,我假设您只想要一个带有给定atype_codemodule

那么您应该使用Single/SingleOrDefaultFirst/FirstOrDefault

String firstModule = dt.AsEnumerable()
                       .Where(r => r.Field<string>("atype_code") == aTypeCode.Trim())
                       .Select(r => r.Field<string>("module"))
                       .FirstOrDefault();
// or
String singleModule = dt.AsEnumerable()
                       .Where(r => r.Field<string>("atype_code") == aTypeCode.Trim())
                       .Select(r => r.Field<string>("module"))
                       .SingleOrDefault();

Enumerable.Single 如果有多个匹配元素,则抛出异常。这对于验证数据很有用。

编辑

这是查询语法:

IEnumerable<String> modules =  
    from myAccType in dt.AsEnumerable()
    where myAccType.Field<string>("atype_code") == aTypeCode.Trim()
    select myAccType.Field<string>("module");
String module = modules.FirstOrDefault(); // returns null if no matching modules were found

【讨论】:

  • 显示错误无法将类型“System.Data.DataRow”转换为“String”
  • @user1227467:编辑了我的答案。
  • @user1227467:不客气,记得点击复选标记accept the answer
猜你喜欢
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多