2016-12-02 57 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