开发者

Problem figuring out how if I am on the first row and column of a datatable?

开发者 https://www.devze.com 2023-02-11 06:43 出处:网络
.NET 2.0 Trying to find if I am on the first row so I can do a comparison foreach(DataRow row in tbl.Rows) {开发者_如何学C

.NET 2.0 Trying to find if I am on the first row so I can do a comparison

foreach(DataRow row in tbl.Rows) {开发者_如何学C
    if (row<something> == "first row") { continue; }

    foreach(DataColumn col in tbl.Columns) {
        if (something == "first column) { continue; }

....

But it is escaping me.


Quick 'n' dirty says you can throw an int counter in there.

int rowCounter=0;
foreach(DataRow row in tbl.Rows) 
{  
    rowCounter++;
    if (rowCounter==1) { continue; }
    ...

    //do the same for a columnCounter to get your first-column first-row
}


You can use Linq to do that:

foreach(DataRow row in tbl.Rows.Cast<DataRow>().Skip(1)) {

foreach(DataColumn col in tbl.Columns.Cast<DataColumn>().Skip(1)) {

or you can compare current Row/Column with first row or column

foreach(DataRow row in tbl.Rows) {
if (tbl.Rows[0] == "first row") { continue; }

foreach(DataColumn col in tbl.Columns) {
    if (tbl.Columns[0] == "first column) { continue; }

or you can use indexer to access it (this way is faster way to access rows)

for(int rowIndex = 0; rowIndex < tbl.Rows.Count; rowIndex++)
{
    if(rowIndex == 0) return;
    var row  = tbl.Rows[rowIndex];
}


Wont a better way be using

bool isFirstReached = false;
foreach (DataRow datarow in datatable.Rows)
{
    foreach (DataColumn datacolumn in datarow.Table.Columns)
    {
        if (!isFirstReached)
        {
            isFirstReached = true;
            continue;
        }
    }
}

unless you prefer for rather than foreach

for (int i = 0; i < datatable.Rows.Count; i++)
{
    for (int j = 0; j < datatable.Columns.Count; j++)
    {
        if (j == 0 && i == 0)
        {
            continue;
        }
    }
}


Could you use a counter like so?

        var tbl = new DataTable();
        int row = -1;
        int column = -1;
        foreach (DataRow row in tbl.Rows)
        {
            row++;
            if (row == 0)
            {
                continue;
            }

            foreach (DataColumn col in tbl.Columns)
            {
                column++;
                if (column  == 0)
                {
                    continue;
                }

            }
        }


Actually the easiest and safest way I found that someone posted on here, but removed it was:

foreach (DataRow row in tbl.Rows) {
    if (tbl.Rows.IndexOf(row) < 1)
    continue;

foreach (DataColumn col in tbl.Columns) {
    if (tbl.Columns.IndexOf(col) < 1)
    continue;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号