使用DataTable.Select()获取行旁边的行 [英] Get the row next to the row got with DataTable.Select()

查看:226
本文介绍了使用DataTable.Select()获取行旁边的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有DataTable对象与下一个数据:

  Id值
1 val1
3 val2
2 val3

我下一步选择一行:

  table.Select(Id = 1); 

此查询给了我行

  1 val1 

接下来,我想在选中的行旁边一个,即行

  3 val2 

我可以这样做吗?可能吗?
也许在表中有一些行的位置,可以通过增加这个值来选择下一行?

解决方案

DataTable.Rows.IndexOf()是我唯一可以想到的。



如何:

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

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

示例:

 code> 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]};

//添加一些数据
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]);

Linqpad中的输出


DataRow

ID 4

AnotherID 13

内容4


希望有助于


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?

解决方案

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

这篇关于使用DataTable.Select()获取行旁边的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆