在代码中使用自定义排序的C#datatable
我有一个C#数据表,目前的排序如下 使用此代码在代码中使用自定义排序的C#datatable,c#,sorting,gridview,datatable,C#,Sorting,Gridview,Datatable,我有一个C#数据表,目前的排序如下 使用此代码 customTable.DefaultView.Sort = "Module DESC"; 我想实现的是将简介条目保持在顶部,但其余条目应以1开头,以4结尾,是否还有其他方法可以应用于此,或者我需要进行自定义编码 datatable是在代码中组装的,它不是来自任何数据源 您可以使用LINQ: customTable = customTable.AsEnumerable() .Select(row => new {
customTable.DefaultView.Sort = "Module DESC";
我想实现的是将简介条目保持在顶部,但其余条目应以1开头,以4结尾,是否还有其他方法可以应用于此,或者我需要进行自定义编码
datatable是在代码中组装的,它不是来自任何数据源 您可以使用LINQ:
customTable = customTable.AsEnumerable()
.Select(row => new
{
row,
module = row.Field<string>("Module").TryGetInt()
})
.OrderBy(x => x.module.HasValue) // all numbers come last (true higher than false)
.ThenBy(x => x.Module.GetValueOrDefault()) // order numbers ascending
.Select(x => x.row)
.CopyToDataTable();
创建另一列“SortOrder”……适当填充,在其上排序您还可以创建一个temp
DataTable
。选择所需的临时排序,然后选择CopyToDataTable()。有些答案应该会有所帮助。
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}