C#对象列表未按几个对象排序

时间:2016-12-02 13:48:04

标签: c# linq lambda

我有List<CableList>CableList有一个名为Location的属性,它是一个对象,具有一个名为Facility的属性。 Facility也是一个对象。

我想按Facility.FacilityTitle订购。 FacilityTitle是一个字符串。

我在做

Runlist.OrderBy(x=> x.Location.Facility.FacilityTitle)
    .Skip(variable)
    .Take(Paginationnum)
    .ToList();

这将返回列表,但FacilityTitle未对其进行排序。

2 个答案:

答案 0 :(得分:1)

这里有Linq对象的例子。 ToList确实没有改变列表的顺序。

List<CableList> Runlist = new List<CableList>
{
    new CableList { Location = new Location 
    { Facility = new Facility { FacilityTitle = "titel3"  }}},
    new CableList { Location = new Location 
    { Facility = new Facility { FacilityTitle = "titel2"  }}},
    new CableList { Location = new Location 
    { Facility = new Facility { FacilityTitle = "titel5"  }}},
    new CableList { Location = new Location 
    { Facility = new Facility { FacilityTitle = "titel1"  }}},
    new CableList { Location = new Location 
    { Facility = new Facility { FacilityTitle = "titel9"  }}}
};

System.Diagnostics.Debug.WriteLine("Before order:");
foreach (var itm in Runlist)
    System.Diagnostics.Debug.WriteLine(itm.Location.Facility.FacilityTitle);

var orderedResult =  Runlist.OrderBy(x => x.Location.Facility.FacilityTitle)
    .Skip(1)
    .Take(4)
    .ToList();

System.Diagnostics.Debug.WriteLine("After order:");
foreach (var itm in orderedResult)
    System.Diagnostics.Debug.WriteLine(itm.Location.Facility.FacilityTitle);

输出:

Before order:
titel3
titel2
titel5
titel1
titel9
After order:
titel2
titel3
titel5
titel9

答案 1 :(得分:-3)

当您使用ToList()方法时,它会将您的序列转换为非提示列表。 请改用此代码:

IEnumerable<CableList> list=Runlist.OrderBy(x=> x.Location.Facility.FacilityTitle)
    .Skip(variable)
    .Take(Paginationnum);