vb.net 如何从数据表中选择列值在列表中的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30872137/
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
How to select rows from a DataTable where a Column value is within a List?
提问by sab669
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this:
假设您有一个 SQL 表,并且您想查找特定列可能是 3 个选项之一的所有行。你可以这样写:
SELECT * FROM MyTable WHERE uid IN (123, 456, 789)
That's effectively what I want to do with a DataTablein VB. I saw this post:
Query rows that the datatable field contain any item in the list<string>
这实际上是我想要DataTable在 VB 中使用 a 做的事情。我看到了这篇文章:
查询数据表字段包含列表中任何项目的行<string>
Which seemed to be exactly what I wanted, but it's not working as I expected it to. I basically just used a C# -> VB converter and plugged in my variables and came up with this:
这似乎正是我想要的,但它并没有像我预期的那样工作。我基本上只是使用了一个 C# -> VB 转换器并插入了我的变量并想出了这个:
Dim item = From a In dtCodes.AsEnumerable() Where
lstCodes.Any(Function(x) a.Field(Of String)
("Code").ToUpper().Contains(x.ToUpper())) Select a
dtCodesis a DataTable with a column Codesin it. lstCodesis a List(Of String)with some values in it.
dtCodes是一个包含一列的数据表Codes。lstCodes是List(Of String)带有一些值的。
itemjust has all of the rows from dtCodesthough, regardless of whether or not their Codecolumn value exists in lstCodes.
item只包含来自的所有行dtCodes,无论它们的Code列值是否存在于lstCodes.
What am I missing?
我错过了什么?
edit; Note that I don't haveto use LINQ, if there's an easier or better way.
编辑; 请注意,我不具备使用LINQ,如果有一个更简单的或更好的办法。
回答by clweeks
In the past, I've done this sort of like this:
过去,我做过这样的事情:
Dim item = From r as DataRow in dtCodes.Rows
Where lstCodes.contains(r.Item("Codes"))
Select r
Does that work?
那样有用吗?
回答by Matt Wilko
The code you have looks ok to me. I tried out this test and it (correctly) prints out
您拥有的代码对我来说看起来不错。我尝试了这个测试,它(正确)打印出来
a2
b1
Dim dtCodes As New DataTable
dtCodes.Columns.Add(New DataColumn("Code"))
dtCodes.Rows.Add("a1")
dtCodes.Rows.Add("a2")
dtCodes.Rows.Add("b1")
dtCodes.Rows.Add("b2")
Dim lstCodes As New List(Of String)
lstCodes.Add("b1")
lstCodes.Add("c1")
lstCodes.Add("a2")
Dim item = From a In dtCodes.AsEnumerable()
Where lstCodes.Any(Function(x) a.Field(Of String)("Code").ToUpper().Contains(x.ToUpper()))
Select a
For Each itm In item
Debug.WriteLine(itm("Code").ToString)
Next
回答by CrazyPaste
Here's a lamba expression that should also work.
这是一个也应该有效的 Lamba 表达式。
Dim item = dtCodes.Select.Where(Function(x As DataRow) lstCodes.Contains(x.Item("Codes")))

