如何在 VB.NET 中使用 LINQ 按列值查找数据表行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8769600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:51:45  来源:igfitidea点击:

How to Find a DataTable Row by Column Value Using LINQ in VB.NET

vb.netlinqdatatablelinq-to-objectsdatarow

提问by Mike Rebosse

Hello I have a Dynamic DataTable Created at runtime. The Setup is like so

您好,我有一个在运行时创建的动态数据表。设置是这样的

Id |  Name  | Age
-----------------
3  |  Mike  | 21
6  |  John  | 43
8  |  Sara  | 34

What I am trying to do is come up with a linq statement I could use to find and update specific rows.

我想要做的是想出一个 linq 语句,我可以用它来查找和更新特定的行。

Such as a statement to change AGE to '33' WHERE ID = '3'

比如把AGE改为'33' WHERE ID = '3'的语句

My code So far is:

我的代码到目前为止是:

-[VB.NET]-
Dim MyRow As DataRow = From column In MyTable.Rows Where column("Id") = 3
MyRow(0)("Age") = 33

But this is not updating my DataTable entry. Any Help would be appreciated. Thank you.

但这并没有更新我的 DataTable 条目。任何帮助,将不胜感激。谢谢你。

回答by adatapost

Correct me if I'm wrong. Take a look at:

如果我错了纠正我。看一眼:

Dim row As DataRow = (From column In MyTable.Rows Where column("Id") = 3).FirstOrDefault()
If Not IsNothing(row) Then
row("Age") = 33
End If

OR you may try DataTable.Select() method.

或者您可以尝试 DataTable.Select() 方法。

Dim rows=MyTable.Select("ID=3")

回答by John Woo

this is not LINQbut filtering datatable.

这不仅仅是LINQ过滤数据表。

Dim iRow() As DataRow = ParticularSource.Tables(ParticularTable).Select(
    String.Format("ItemID = '{0}'", ParticularID))

ParticularSourceis the name of my Dataset
ParticularTableis the name of my Datatable
ItemIDis the field where I Searched on
ParticularIDis the value to be searched

ParticularSource是我的数据集
ParticularTable的名称是我的数据表的名称
ItemID是我搜索的字段
ParticularID是要搜索的值

iRow(0)("Age") = NewValue
ParticularSource.Tables(ParticularTable).AcceptChanges()