繁体   English   中英

如何将面向列的C#数据表中的行范围从一列复制到另一列?

[英]How to copy a row range from one column to others in a column oriented c# datatable?

据我了解,数据表的条目通常是面向行的,其中列具有一定含义,而行则表示不同的数据集。 这也是为什么使用DataTable.Rows.Add()添加实际数据的原因。在我的情况下,这些列被视为一个数据集,我需要从这些列中提取数据以用于其他区域。

我使用LINQ和Lambda表达式的组合来获取一个完整列的数据:

int curCol = 4;
int maxRows = 55;
byte[] values = new byte[maxRows];
values = dt.Rows.Cast<DataRow>().Select<DataRow, byte>(row => Convert.ToByte(row[curCol])).ToArray();

但这就是我对LINQ和Lambda的幸运结束的地方。 我尝试实现一个复制例程,以选择与源不同但在特定行中具有相同值的列。 然后,我选择要复制到所有其他匹配列的行范围。 这是一个如何与for和if语句一起使用的示例:

const int numCols = 10;
int curCol = 2;
int searchRow = 1;
int startRow = 3;
int numRows = 25;
byte val = (byte)dt.Rows[searchRow][curCol]; 
// iterate through all columns
for (int col = 0; col < numCols; col++)
{
    // look for "other" columns with the same value in the searchRow of interest
    if (col != curCol && val == (byte)dt.Rows[searchRow][col])
    {
        // iterate through the given row range (startRow and numRows)
        for (int row = startRow; row < startRow+numRows; row++)
        {
            // copy from current column
            dt.Rows[row][col] = dt.Rows[row][curCol];
        }
    }
}

我想知道是否有更好,更有效的方法来实现使用LINQ和Lambda表达式?

示例数据

1 2 3 4 ... // cols 0 .. 3 in row 0
5 5 6 6 ... // cols 0 .. 3 in row 1
0 0 1 0 ... // ...
7 0 8 0 ...
9 0 9 0 ...
. . . .

预期结果

1 2 3 4 ...
5 5 6 6 ... // value in col 3 is equal to value in col 2
0 0 1 0 ...
7 0 8 8 ... // value from col 2 copied to col 3
9 0 9 9 ... // value from col 2 copied to col 3
. . . .

我希望这会使它更容易理解。 第2列和第3列按行1中的值进行分组/链接,并且由于第2列是源,因此应将所选行范围内的其他值复制到链接的列中。 只是为了阐明这一点。 上面的If / For实现正是这样做的。 我只是希望使用LINQ / Lambda快捷方式或其他更有效的执行方式。

我看不到太多:

DataTable dt = new DataTable();

            const int numCols = 10;
        int curCol = 4;
        int searchRow = 1;
        int startRow = 3;
        int numRows = 25;
        int hashVal = dt.Rows[searchRow][curCol].GetHashCode();
        var thisValue = dt.Rows[searchRow][curCol];
        //iterate cols and rows
        for(int c = 0; c < numCols; c++)
        {
            for(int r = startRow; r < startRow + numRows; r++)
            {
                int thisHash = dt.Rows[r][c].GetHashCode();
                if (thisHash == hashVal)
                {
                    dt.Rows[r][c] = thisValue;
                }
            }
        }

没什么动摇的。 不过,我不明白的是,您似乎正在寻找匹配值以复制匹配值-默认情况下,如果该值已经等于源行/行,那么为什么需要复制(因为已经相等)? 也许您出于演示目的而进行了简化,但是我认为没有必要...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM