据我所知,数据表的条目通常是面向行的,其中列具有特定含义,行指示不同的数据集。 这也是使用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快捷方式或其他更有效的执行方式。
答案 0 :(得分:0)
我看不太多:
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;
}
}
}
没有什么是震撼人心的。但是,我不明白,你似乎是为了复制匹配的值而找到匹配的值 - 默认情况下,如果值已经等于源行/列,那么为什么需要复制(因为它已经相等)?也许你为了演示目的进行了简化,但我没有看到这个需要...