使用特定的值序列重新排序数据表行
reorder datatable rows with a specific sequence of values
我有一个如下所示的数据表:
IDDOC DOCNAME
1 mydoc1
153 mydoc2
98 mydoc3
1327 mydoc4
241 mydoc5
我想找到一种方法,根据特定的 ID 序列重新排序该数据表中的行
例如,对于这样的序列:1327,98,1,预期输出将是:
IDDOC DOCNAME
1327 mydoc4
98 mydoc3
1 mydoc1
153 mydoc2 (not in my sequence so this row comes at the end)
241 mydoc5 (not in my sequence so this row comes at the end)
我正在考虑创建一个新的空数据库并添加 IDDOC 排在第一位的行,然后是序列中的第二位,然后是第三位,最后是我的序列中不存在的所有行,但我想知道是否有更清洁的东西已经存在。
非常感谢您的帮助!
您可以使用这种方法:
dt = dt.AsEnumerable()
.OrderBy(r => r.Field<int>("IDDOC") == 1327 ? 0 : 1)
.ThenBy(r => r.Field<int>("IDDOC") == 98 ? 0 : 1)
.ThenBy(r => r.Field<int>("IDDOC") == 1 ? 0 : 1)
.CopyToDataTable();
如果您想要一个动态的 id 列表,并且 DataTable
应该按以下顺序排序:
List<int> docIdSequence = new List<int>{ 1327, 98, 1 };
dt = dt.AsEnumerable()
.OrderBy(r => {
int ix = docIdSequence.IndexOf(r.Field<int>("IDDOC"));
return ix >= 0 ? ix : int.MaxValue;
})
.CopyToDataTable();
请注意,如果没有输入 DataRows
,CopyToDataTable
将抛出异常。所以你必须在使用上面的代码之前检查dt.Rows.Count > 0
。
我有一个如下所示的数据表:
IDDOC DOCNAME
1 mydoc1
153 mydoc2
98 mydoc3
1327 mydoc4
241 mydoc5
我想找到一种方法,根据特定的 ID 序列重新排序该数据表中的行
例如,对于这样的序列:1327,98,1,预期输出将是:
IDDOC DOCNAME
1327 mydoc4
98 mydoc3
1 mydoc1
153 mydoc2 (not in my sequence so this row comes at the end)
241 mydoc5 (not in my sequence so this row comes at the end)
我正在考虑创建一个新的空数据库并添加 IDDOC 排在第一位的行,然后是序列中的第二位,然后是第三位,最后是我的序列中不存在的所有行,但我想知道是否有更清洁的东西已经存在。 非常感谢您的帮助!
您可以使用这种方法:
dt = dt.AsEnumerable()
.OrderBy(r => r.Field<int>("IDDOC") == 1327 ? 0 : 1)
.ThenBy(r => r.Field<int>("IDDOC") == 98 ? 0 : 1)
.ThenBy(r => r.Field<int>("IDDOC") == 1 ? 0 : 1)
.CopyToDataTable();
如果您想要一个动态的 id 列表,并且 DataTable
应该按以下顺序排序:
List<int> docIdSequence = new List<int>{ 1327, 98, 1 };
dt = dt.AsEnumerable()
.OrderBy(r => {
int ix = docIdSequence.IndexOf(r.Field<int>("IDDOC"));
return ix >= 0 ? ix : int.MaxValue;
})
.CopyToDataTable();
请注意,如果没有输入 DataRows
,CopyToDataTable
将抛出异常。所以你必须在使用上面的代码之前检查dt.Rows.Count > 0
。