如何在每个类别的末尾添加空数据行

时间:2015-10-10 23:40:57

标签: c# datatable

我在C#应用程序中有DataTable

DataTable有一个名为“类别”的列,有10个不同的值。

这就是我的DataTable行的样子:

enter image description here

如何在每个类别组之后添加一个空行,以下是我需要的示例:

enter image description here

有任何线索吗?

3 个答案:

答案 0 :(得分:1)

以下是我提出的解决方案:

var insertAtIndexes = dataTable.Rows.Cast<DataRow>()
    .GroupBy(row => row["Category"])
    .Select(rowGroup => rowGroup.Select(row => dataTable.Rows.IndexOf(row) + 1)
    .Max()).ToList();

for (var i = 0; i < insertAtIndexes.Count; i++)
{
    var emptyRow = dataTable.NewRow();
    dataTable.Rows.InsertAt(emptyRow, insertAtIndexes[i] + i);
}

这将在每个类别组之后插入一个空行(这假设您的示例中的行已按类别排序)。我们在for循环中插入,因为当我们在表中插入新行时,需要增加insertAtIndexes以考虑新插入的行。

注意:如果您的DataTable列允许空值,则只能插入dataTable.NewRow()。如果他们没有,那么做这样的事情来分配默认值。您将没有空白行,因为您的非字符串列不允许空值:

for (var i = 0; i < insertAtIndexes.Count; i++)
{
    var emptyRow = dataTable.NewRow();
    dataTable.Rows.InsertAt(SetDefaultValues(emptyRow), insertAtIndexes[i] + i);
}

static DataRow SetDefaultValues(DataRow row)
{
    row.SetField(1, 0);
    row.SetField(2, 0);
    row.SetField(3, 0);
    row.SetField(4, 0);
    return row;
}

答案 1 :(得分:0)

for (int i = dataTable.Rows.Count - 1; i > 0; i--)
{
    if ((string)dataTable.Rows[i]["Category"] != (string)dataTable.Rows[i - 1]["Category"])
    {
        var row = dataTable.NewRow();
        row["Category"] = string.Empty;
        dataTable.Rows.InsertAt(row, i);
    }
}

答案 2 :(得分:0)

//Include Two Empty Rows After Each WCG
var insertAtIndexes = ds.Tables["Capacity Progress to Due Date"].Rows.Cast<DataRow>()
//.GroupBy(row => new { wcg = row.Field<int>("WcgName"), Date = Convert.ToDateTime(row.Field<int>("DueDate").ToString()) })
.GroupBy(row => row["WcgName"])
.Select(rowGroup => rowGroup.Select(row => ds.Tables["Capacity Progress to Due Date"].Rows.IndexOf(row) + 1)
.Max()).ToList();

for (var i = 0; i < insertAtIndexes.Count; i++){
    var emptyRow = ds.Tables["Capacity Progress to Due Date"].NewRow();
    var secondemptyRow = ds.Tables["Capacity Progress to Due Date"].NewRow();
    ds.Tables["Capacity Progress to Due Date"].Rows.InsertAt(emptyRow, insertAtIndexes[i] + i + i);
    ds.Tables["Capacity Progress to Due Date"].Rows.InsertAt(secondemptyRow, insertAtIndexes[i] + i + i);
}