如何使用 linq 在数据行上选择字段
我有这个 linq 查询:
string title = from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title;
我想提取行上的字段标题(来自数据库)(行数将为 1,而不是更多,所以我将其放在字符串上而不是字符串 [] 中。
我怎样才能 让
VStudio 说 DataRow 不包含 Title 的定义,但数据库中存在 Title 字段,这
我感到困惑:)
I have this linq query :
string title = from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title;
and I'd like to extract the field Title (from Database) on the row (rows will be 1, not more, so that's I put on a string and not in a string[].
How can I do it?
VStudio says that DataRow doesnt contain the definition of Title, but the field Title exist on the database.
I making confusion :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如 Frédéric Hamidi 所说,您不需要 LINQ。
但是,如果您仍然想这样做(矫枉过正)并且您知道总是有一个表包含一行,请执行以下操作:
或者
我使用
DataSet
因为我不知道如何你的对象是结构化的。As Frédéric Hamidi said, you don't need LINQ.
However, if you still want to do it that way (overkill) and you know that there is always a single table with a single row, do:
or
I used a
DataSet
because I don't know how your object is structured.您不需要 LINQ,因为您只想获取集合中第一行的
Title
字段:You don't need LINQ since you only want to fetch the
Title
field of the first row in the collection:尝试
Linq 返回一个可枚举集合,因为它不知道只有一项。调用 First 方法将返回查询中的第一项。
编辑:等一下,我公然错过了您最初提到的问题(但您仍然需要上述内容)!
数据行包含字段,而不是属性本身。你需要做的是
所以你的整个查询将是
try
Linq returns an enumerable collection as it doesn't know there will be only one item. Calling the First method will return the first item from the query.
Edit: Hang on, I have blatantly missed the problem you originally mentioned (but you'll still need the above)!
A data row contains fields, not properties as such. What you'll need to do is
So your entire query will be
最好使用 FirstOrDefault,以防没有行:
It's better to use FirstOrDefault, in case there are no rows:
通常,如果您需要执行此类操作,您可以将 DataRow 对象强制转换为与数据库中的表相对应的强类型对象。
我假设有一个“Book”类,其中包含“Title”字段:
希望这会有所帮助。
Usually, if you need to perform such an action, you would cast the DataRow object to your strongly typed object corresponding with the table in your database.
I assume there is a class "Book" which contains the field "Title":
Hope this helps.