从下面的代码我得到第一列的排序行。如何通过跳过第一行来排序
var Rows = (from row in datatable.AsEnumerable()
orderby row[0] ascending
select row);
注意:我想通过仅考虑第一列来排序行。请不要考虑名称和城市列。 (说名字和城市不存在)。
原始表
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
答案 0 :(得分:3)
如果你使用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]));
答案 1 :(得分:1)
您可以通过布尔值进行排序,例如使用条件运算符:
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;
答案 2 :(得分:0)
你可以尝试这个逻辑:
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]);
答案 3 :(得分: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]));
答案 4 :(得分:-1)
您必须按条件使用多个订单
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();