Get the row next to the row got with DataTable.Select()

白昼怎懂夜的黑 提交于 2019-12-11 07:56:59

问题


I have DataTable object with next data:

Id Value
1   val1
3   val2
2   val3

I'm selecting one row next way:

 table.Select("Id=1");

This query gives me row

 1 val1

And next I want to take the row next to selected one, i.e. row

 3 val2

Can I do this somehow? Is it possible? Maybe there is something like row's position in a table, that I can use to select next row by incrementing this value?


回答1:


DataTable.Rows.IndexOf() is the only thing that I can think of.

How:

var rows=table.Select("Id=1");
var indexOfRow=table.Rows.IndexOf(rows[0]); //since Id only 1 match

var nextRow=table.Rows[indexOfRow+1];

Example:

    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof (int));
    dt.Columns.Add("AnotherID", typeof(int));
    dt.Columns.Add("Content", typeof(string));
    dt.PrimaryKey = new[] {dt.Columns["ID"]};

    // Add some data
    dt.Rows.Add(1, 10, "1");
    dt.Rows.Add(2, 11, "2");
    dt.Rows.Add(3, 12, "3");
    dt.Rows.Add(4, 13, "4");

    var index = dt.Rows.IndexOf(dt.Rows.Find(3));

    // index is 2

    Console.WriteLine(dt.Rows[index+1]);

Output in Linqpad

DataRow
ID 4
AnotherID 13
Content 4

Hope that helps



来源:https://stackoverflow.com/questions/10121747/get-the-row-next-to-the-row-got-with-datatable-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!