.net 在数据表上查找行索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9168725/
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
Find Row Index on DataTable
提问by Aaron
Is it possible to get the row index of a DataTable so that you can access the previous and next row? For example I have a DataTable that contains two columns ChapterTitle and PageURL. This is for a table of contents of a book. ChapterTitle is the chapter name and PageURL is an HTML page that contains the chapter (chaptername.html). When going into one chapter of the book I want to be able to tell which is the next and previous chapter.
是否可以获取 DataTable 的行索引,以便您可以访问上一行和下一行?例如,我有一个包含两列 ChapterTitle 和 PageURL 的数据表。这是一本书的目录。ChapterTitle 是章节名称,PageURL 是包含该章节的 HTML 页面 (chaptername.html)。当进入本书的某一章时,我希望能够分辨哪一章是下一章和上一章。
After finding the chapter that I'm currently in how can get the next and previous rows?
找到我当前所在的章节后,如何获取下一行和上一行?
ChapterTable.Select("PageURL = '" & PageURL& "'")
回答by Jeremy Thompson
Private Sub LoadDataAndFindRow
Dim dt As New DataTable()
dt.Columns.Add("ChapterTitle")
dt.Columns.Add("PageURL")
Dim dr As DataRow = dt.NewRow()
dr(0) = "Aarons Book"
dr(1) = "www.AaronsBook.com"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr(0) = "Tims Book"
dr(1) = "www.TimsBook.com"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr(0) = "vincents Book"
dr(1) = "www.vincentsBook.com"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr(0) = "Xi's Book"
dr(1) = "www.XisBook.com"
dt.Rows.Add(dr)
Dim i As Integer = FindRow(dt, "Tims Book")
Dim prevRowID As Integer = i - 1
Dim nextRowID As Integer = i + 1
End Sub
Function FindRow(ByVal dt As DataTable, ByVal chapterTitle As String) As Integer
For i As Integer = 0 To dt.Rows.Count
If dt.Rows(i)("ChapterTitle") = chapterTitle Then Return i
Next
Return -1
End Function
回答by Nathan Teague
If you set the dt.Columns.PrimaryKey() when you draw up the table, you can just use findby(pk) if you set that then you can use LINQ easily, just: ' we'll name the datatable chapters to keep readable:
如果您在绘制表格时设置了 dt.Columns.PrimaryKey(),那么您可以使用 findby(pk) 如果您设置了它,那么您可以轻松地使用 LINQ,只需:' 我们将命名数据表章节以保持可读性:
dim query = from chapters in dt.AsEnumerable _
where chapters("chapterTitle").equals(<<your criteria>>) _
select chapters
newDT = iif(chapters.count > 0, chapters.copyToDataTable(), nothing)
You can modify or just get the chapters.toDataRow..etc.
您可以修改或仅获取章节.toDataRow.. 等。
HTH
HTH

