【发布时间】:2017-02-04 01:02:08
【问题描述】:
我在 C# 应用程序中有 DataTable。
这个DataTable 有一个名为“Category”的列,并且有 10 个不同的值。
这就是我的 DataTable 行的样子:
如何在每个类别组之后添加一个空行,这是我需要的示例:
有什么线索吗?
【问题讨论】:
-
以下答案是否有帮助?
我在 C# 应用程序中有 DataTable。
这个DataTable 有一个名为“Category”的列,并且有 10 个不同的值。
这就是我的 DataTable 行的样子:
如何在每个类别组之后添加一个空行,这是我需要的示例:
有什么线索吗?
【问题讨论】:
这是我想出的解决方案:
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()。如果他们不这样做,那么做这样的事情来分配默认值。您不会有 blank 行,因为您的非字符串列不允许空值:
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;
}
【讨论】:
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);
}
}
【讨论】:
//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);
}
【讨论】: