2016-10-27 75 views
1

我想按組名稱對SelectListItems列表進行排序。我能夠應用組並根據組進行排序,但似乎無法改變哪個組首先出現。即使按組名稱排序,組「B」也始終顯示在組「A」之前。如何按組名稱對SelecListItem列表進行排序

List<SelectListItem> locationList = new List<SelectListItem>(dynamicTypes.Where(p => p.DynamicTypeId == DynamicTypes.Areas && p.ParentTypeId != null).Select(p => new SelectListItem 
     { 
      Text = p.NameEnglish, 
      Value = p.Id.ToString() 
     })); 
SelectListGroup groupA = new SelectListGroup(); 
groupA.Name = "A"; 
SelectListGroup groupB = new SelectListGroup(); 
groupB.Name = "B"; 
foreach(SelectListItem sel in locationList) 
{ 
    if (sel.Text == "Aylmer, east of Vanier" || sel.Text == "Aylmer, west of Vanier" || sel.Text == "Gatineau, east of Paiement" || sel.Text == "Gatineau, west of Paiement" 
     || sel.Text == "Hull" || sel.Text == "Parc de la Montagne" || sel.Text == "Plateau") 
    { 
     sel.Group = groupA; 
    } 
    else 
    { 
     sel.Group = groupB; 
    } 
} 

locationList.OrderBy(p => p.Group.Name); 
+1

請出示你定義和填充'locationList' –

+1

'locationList = locationList.OrderBy(P => p.Group.Name);'可能需要在結束ToList或ToArray。 – Gusman

+3

'locationList = locationList.OrderBy(p => p.Group.Name);'(你必須在排序後分配它)。 –

回答

2

OrderBy到位不排序,它會創建一個新的列表作爲返回值,所以你需要將其分配給一個變量,以便能夠使用它:

locationList = locationList.OrderBy(p => p.Group.Name); 

原來這裏locationList將被排序列表覆蓋。如果您需要原始列表中使用新的變量:

var sortedList = locationList.OrderBy(p => p.Group.Name); 
相關問題