【发布时间】:2019-06-12 11:18:53
【问题描述】:
正如标题所说,我需要对我的 DataTable 进行自定义排序,其中我使用 DataRow 的索引,结果应该是 EnumerableRowCollection 或 OrderedEnumerableRowCollection,因为我想要一个表(默认顺序)和一个 DataView(自定义顺序)。
我想要的顺序:首先按几列排序(例如姓名,姓氏,...)。然后拆分table1和table2中的表格(只是表格的一半)。然后交替从第一个和第二个表中选择。结果应该是
table1 的行
table2 的行
table1的行
原表不应该受到影响,结果应该是对原表的引用。
internal static DataView GetSortedView(this DataTable table)
{
return table.GetSortedTable().AsDataView();
}
internal static void OrderedEnumerableRowCollection<DataRow> GetSortedTable(this DataTable table)
{
int half = table.Rows.Count / 2;
//sort columns by name for example
var enumerable = table.AsEnumerable().OrderBy(field => field.Field<string>("Name"), new NaturalStringComparer());
//here is the tricky part
enumerable= enumerable.OrderBy(row =>
{
int myIndex = ?; //I cannot use table.Rows.IndexOf(row) because the order of the current OrderedEnumerableRowCollection should be used and not the default order of the table
bool upperHalf = myIndex > half;
if (upperHalf)
{
myIndex -= half;
}
return new CustomSortItem(myIndex , upperHalf);
}, new CustomSort());
return enumerable;
}
我尝试先为索引添加一个新列,但这并没有真正起作用,因为当我尝试删除该列时,最后由于延迟加载而收到异常。
internal static void OrderedEnumerableRowCollection<DataRow> GetSortedTable(this DataTable table)
{
//create another column for an index
string tempSortName = "[TEMP_SORT]";
table.Columns.Add(tempSortName);
//sort columns by Name for example
var enumerable= table.AsEnumerable().OrderBy(field => field.Field<string>("Name"), new NaturalStringComparer());
//set the temporary order (index)
int count = 0;
foreach(DataRow row in enumerable)
{
row[tempSortName] = count++;
}
//here is the tricky part
int half = table.Rows.Count / 2;
enumerable= enumerable.OrderBy(row =>
{
int myIndex = int.parse(row[tempSortName].ToString()); //exception here. column not found
bool upperHalf = myIndex > half;
if (upperHalf)
{
myIndex -= half;
}
return new CustomSortItem(myIndex , upperHalf);
}, new CustomSort());
table.Columns.Remove(tempSortName);
return enumerable;
}
我也不想使用 IEnumerable,因为当我创建 DataView 时,我必须创建另一个表才能创建一个,然后引用丢失(view.Table 不是原始表,只是没有参考)。
IEnumerable<DataRow> enumerable...
enumerable.CopyToDataTable().AsDataView();
// I have to call CopyToDataTable() in order to create a DataView
【问题讨论】: