2016-12-02 66 views
0

我有List<CableList>。​​有一个名为Location的属性,它是一个对象,它具有一个名为Facility的属性。 Facility也是一个对象。我想订购Facility.FacilityTitleFacilityTitle是一个字符串。C#List of Object not order by several objects down

我做

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

这将返回列表中,但它不是由FacilityTitle排序。

+2

那是什么'OrderBy'函数的输出? – RandomStranger

+2

你把它分配给任何东西吗?它会创建一个新的列表。 – juharr

+0

您是否将您的列表对象与它是实例的类相同?你确定位置和设施是否为空?如果这是Linq to Sql(EF),则应该添加Include以检索Location和Facility。 – Max

回答

-3

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

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

这是不正确的。 ToList保留订单。 – Jakotheshadows

+1

“它将您的序列转换为未排序的列表” - 我不确定您的意思。调用ToList只是将IEnumerable转换为List对象。订购将不会改变,所以如果物品被订购之后,他们将在相同的顺序后... – Chris

+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