[英]Is there a way to get the last non-null values of each column in a C# DataTable and display them as a single row?
我想獲取 DataTable 中每一列的最后一個非空值並用它們創建一行。
示例代碼:
DataTable temp; // temp is the DataTable shown on the left side in the "Current Result" section
DataTable temp2; // stores the newly create DataTable row
foreach(DataRow row in temp.Rows){
object[] Item = new object[] {};
foreach(DataColumn col in temp.Columns){
if (row[col] != null || row[col] != DBNull.Value || !String.IsNullOrWhiteSpace(row[col].ToString()))
{
Array.Resize(ref Item, Item.Length + 1);
Item[Item.Length - 1] = row[col];
}
}
temp2.Rows.Add(Item);
}
我的代碼當前將所有單元格從一個 DataTable 復制到另一個,包括其中沒有存儲任何值的單元格。
在下面的照片中,除了每列的最后一個非值之外,我將所有單元格塗黑。 我希望將顯示的值存儲並顯示為單行。
在我看來,您只是想在temp2
表中添加一行,該表的每一列都有最后一個非空值。 如果是這種情況,那么您可以使用Columns.Count
大小初始化object[]
,並且我們可以使用列索引遍歷列,這允許我們在找到非當前行中它的空值:
DataTable temp = new DataTable();
DataTable temp2 = temp.Clone();
// A single row of data that is 'Columns.Count' long
object[] lastNonNullValues = new object[temp.Columns.Count];
foreach (DataRow row in temp.Rows)
{
// Loop through columns using the column index rather than a foreach
for (int i = 0; i < temp.Columns.Count; i++)
{
var col = temp.Columns[i];
if (row[col] != null || row[col] != DBNull.Value ||
!string.IsNullOrWhiteSpace(row[col].ToString()))
{
// Now we just assign the value at the index for this column
lastNonNullValues[i] = row[col];
}
}
}
// Add our single row to the results table
temp2.Rows.Add(lastNonNullValues);
我不知道問題是否解決了。 她是我解決問題的建議。 我會 go 從最后一行到第一行,因為任務是從每一列中獲取最后一個值,然后循環可能會更糟,就像你從表格的頂部到底部的 go 一樣。 但我認為這也取決於表中的數據。
DataTable temp = yourTable; // the original table
DataTable temp2 = new DataTable();
object[] lastNonNullValues = new object[temp.Columns.Count];
// Index of the last row.
int lastRow = temp.Rows.Count - 1;
// Get from the last row to the first
for (int i = lastRow; i >= 0; i--)
{
// Don't know if necessary but if all columns has an value -> finish.
if (lastNonNullValues.All(x => x != null)) break;
DataRow row = temp.Rows[i];
for (int j = 0; j < temp.Columns.Count; j++)
{
// Continue if some value was written
if (lastNonNullValues[j] != null) continue;
// None of this condition should be true, thas why should change from || to &&
if (row[j] != null && row[j] != DBNull.Value && !string.IsNullOrWhiteSpace(row[j].ToString()))
{
lastNonNullValues[j] = row[j];
}
}
}
temp2.Rows.Add(lastNonNullValues);
當將 if 語句從or更改為and-conjunction時, Rufus L的解決方案也應該起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.