Linq:排序没有第一行的行
本文关键字:一行 排序 Linq | 更新日期: 2023-09-27 18:19:16
从下面的代码我得到排序行第一列。如何通过跳过第一行
进行排序 var Rows = (from row in datatable.AsEnumerable()
orderby row[0] ascending
select row);
注意:我想只考虑第一列来排序。请不要考虑Name和City列。(说姓名和城市不存在)。
原始表ID Name City
----------- --------------------------------
3 Vijendra Delhi
2 Singh Noida
1 Shakya New Delhi
5 Shakya New Delhi
4 Shakya New Delhi
当前O/p ID Name City
----------- --------------------------------
1 Shakya New Delhi
2 Singh Noida
3 Vijendra Delhi
4 Shakya New Delhi
5 Shakya New Delhi
预期O/p ID Name City
----------- --------------------------------
3 Vijendra Delhi
1 Shakya New Delhi
2 Singh Noida
4 Shakya New Delhi
5 Shakya New Delhi
如果使用List:
var newList = new List<DataRow>(){originalList.First()};
newList.AddRange(originalList.Where(x => x.row[0] != originalList.First().row[0]).OrderBy(x => x.row[0]));
您可以按布尔值排序,例如使用条件运算符:
var Rows = from row in datatable.AsEnumerable()
let id = row.Field<int>(0)
orderby id == 3 ? 0 : 1 ascending, id ascending
select row;
这也可以,但我发现条件操作符更具可读性:
orderby id == 3 descending, id ascending
即使它对我来说没有多大意义,如果你想保持第一行总是在顶部,无论内容是什么,你可以使用Object.ReferenceEquals
:
var Rows = from row in datatable.AsEnumerable()
let id = row.Field<int>(0)
let isFirstRow = ReferenceEquals(row, datatable.Rows[0])
orderby isFirstRow descending, id ascending
select row;
您可以尝试以下逻辑:
var firstId = ...
var Rows = (from row in datatable.AsEnumerable()
orderby row[0] == firstId descending, row[0] ascending
select row);
另一个选择是有一个扩展方法:
public static IEnumerable<T> OrderAfterFirst<T, TKey>(this IEnumerable<T> src,
Func<T, TKey> keySelector)
{
// Ensure you don't throw or return null or whatever if the collection is empty
foreach (var first in src.Take(1))
{
yield return first;
}
// Return the rest of the elements ordered
foreach (var x in src.Skip(1).OrderBy(keySelector))
{
yield return x;
}
}
则用法为:
var rows = datatable.AsEnumerable().OrderAfterFirst(row => row[0]);
将除第一行外的所有内容排序,然后将其与第一行合并:
var data = datatable.AsEnumerable();
var firstRow = data.Take(1);
var sorted = data.Skip(1).OrderBy(row=>row[0]);
var rows = firstRow.Concat(sorted);
或作为一个语句:
var rows = data.Take(1).Concat(data.Skip(1).OrderBy(row=>row[0]));
必须使用多个order by条件
var Rows = datatable.AsEnumerable().OrderBy(x => x.Name )
.ThenByDescending(x => x.City )
.ToList();
你也可以使用查询语法说:
var Rows = (from row in datatable.AsEnumerable()
orderby row .Name , row.City descending
select row ).ToList();