OrderBy和ThenBy与匿名类

时间:2016-05-04 16:10:34

标签: c# linq lambda

我有这个:

List<string> lstRanksOrder = new List<string>() { 
  "Captain", "Lieutenant", "Sergeant", "Corporal Master", 
  "Corporal Senior", "Corporal 1", "Corporal", "Civilian Pilot" };

var emp = test
  .ToList()
  .Select(x => new
     {
       EID = x.IBM,
       Description = string.Format("{0} {1}", x.FirstName, x.LastName),
       Group = x.RPosition
     })
  .AsEnumerable()
  .OrderBy(x => lstRanksOrder.IndexOf(x.Group))
  .ThenBy(x => x.Description)
  .Distinct()
  .ToList();

ThenBy条款工作正常,但有没有办法在LastName之前FirstName更改订单,而不将Description更改为Description = string.Format("{0} {1}", x.LastName, x.FirstName)

2 个答案:

答案 0 :(得分:4)

在调用Select扩展名方法之前订购集合:

var emp = test.ToList()
.OrderBy(x => lstRanksOrder.IndexOf(x.RPosition))
.ThenBy(x => x.LastName)
.ThenBy(x => x.FirstName)
.Select(x => new
{
    EID = x.IBM,
    Description = string.Format("{0} {1}", x.FirstName, x.LastName),
    Group = x.RPosition
})
.Distinct()
.ToList();

答案 1 :(得分:1)

在调用Distinct扩展方法之前,

Order然后Select集合:

var emp = test.ToList()
.Distinct()
.OrderBy(x => lstRanksOrder.IndexOf(x.RPosition))
.ThenBy(x => x.LastName)
.ThenBy(x => x.FirstName)
.Select(x => new
{
    EID = x.IBM,
    Description = string.Format("{0} {1}", x.FirstName, x.LastName),
    Group = x.RPosition
})

.ToList();