你可以定制一下
IComparer<T>
根据两个项目在您定义的参考顺序中的位置进行比较。然后,使用比较器对表中的行进行排序。
public class PrecedenceComparer<T> : IComparer<T>
{
private List<T> ReferenceList { get; set; }
public PrecedenceComparer(IEnumerable<T> referenceOrder)
{
if (referenceOrder == null)
throw new ArgumentException(nameof(referenceOrder));
ReferenceList = referenceOrder.ToList();
}
public int Compare(T x, T y)
{
int xIndex = ReferenceList.IndexOf(x);
int yIndex = ReferenceList.IndexOf(y);
if (xIndex >= 0 && yIndex >= 0) return xIndex - yIndex;
if (xIndex >= 0) return -1;
if (yIndex >= 0) return 1;
return 0;
}
}
DataTable
使用比较器就地执行,因此需要从表中获取行,使用比较器对行进行排序,然后将排序的行复制到新表中,如下所示:
public static DataTable SortTable(DataTable table)
{
var comparer = new PrecedenceComparer<string>(new string[] { "foundation", "column", "beam" });
// sort the rows of the original table
var orderedRows = table.Rows.Cast<DataRow>()
.OrderBy(row => (string)row["type"], comparer)
.ThenBy(row => (int)row["vol"]) // secondary sort (delete this line if there isn't one)
;
// copy the sorted data to a new table
DataTable newTable = new DataTable();
foreach (DataColumn col in table.Columns)
{
newTable.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row in orderedRows)
{
DataRow newRow = newTable.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
newRow[i] = row[i];
}
newTable.Rows.Add(newRow);
}
return newTable;
}
https://dotnetfiddle.net/R5ypUo