2012-07-19 71 views
0

我在排序傳遞給視圖的用戶配置文件列表時遇到問題。我想要顯示某個角色中所有用戶的列表,並且我想通過familyName屬性對它們進行排序。對mvc3中的UserProfiles列表進行排序asp.net應用程序

我試過使用OrderBy,但它沒有效果。

代碼控制器

public ActionResult Index() 
    { 
     //get all patients 
     var patients = Roles.GetUsersInRole("user").ToList(); 
     //set up list of patient profiles 
     List<UserProfile> pprofiles = new List<UserProfile>(); 
     foreach (var i in patients) { 
      pprofiles.Add(ZodiacPRO.Models.UserProfile.GetUserProfile(i)); 
     } 
     pprofiles.OrderBy(x => x.familyName); //<-this has no effect the list produced is 
               // exactly the same it was without this line 
     return View(pprofiles); 
    } 

和視圖

<ul id= "patientList"> 

     @foreach (var m in Model) 
      { 
       <li> 
       <ul class="patient"> 
       <li class="ptitle">@m.title</li> 
       <li class="pname"> @Html.ActionLink(@m.givenName + " " + @m.familyName, "View", "Account", new { @username = @m.UserName.ToString() }, new { id = "try" })</li> 
       <li class="pprofile">@Ajax.ActionLink("Profile", "PatientSummary", new { @username = @m.UserName }, new AjaxOptions { UpdateTargetId = "pContent"},new{ @class = "profpic" })</li> 
       </ul> 
       </li>   
      } 
    </ul> 

我需要在多個地方重新使用這一點,可能有大量的用戶,以便在沒有命令他們有時候會很糟糕。我應該怎麼做呢?

回答

2

pprofiles.OrderBy(x => x.familyName);將返回IEnumerable<T>,不對調用它的數組進行排序。

你可以改變你的代碼是這樣的:

public ActionResult Index() 
{ 
    //get all patients 
    var patients = Roles.GetUsersInRole("user").ToList(); 
    //set up list of patient profiles 

    List<UserProfile> pprofiles = new List<UserProfile>(); 
    foreach (var i in patients) { 
     pprofiles.Add(ZodiacPRO.Models.UserProfile.GetUserProfile(i)); 
    }  
    var ordered = pprofiles .OrderBy(x => x.familyName); 

    return View(ordered); 
} 

或者更LINQ的風格方式:

var orderedPatients = Roles.GetUsersInRole("user") 
          .Select(u=>ZodiacPRO.Models.UserProfile.GetUserProfile(u)) 
          .OrderBy(u=>u.FamilyName); 


return View(orderedPatients); 

或者:

var orderedPatients = from u in Roles.GetUsersInRole("user") 
         let userProfile = ZodiacPRO.Models.UserProfile.GetUserProfile(u) 
         order by userProfile.FamilyName 
         select userProfile; 
return View(orderedPatients); 
+1

更確切地說'OrderBy'將返回一個'IOrderedEnumerable ' – Zbigniew 2012-07-19 15:20:44

+0

啊,很好!我去Linq風格的方式,它像一個魅力。謝謝!你能否詳細解釋它是如何工作的?我在猜測選擇遍歷用戶列表並獲取他們的配置文件......或者它是否將返回的用戶列表更改爲UserProfiles列表? – Nieszka 2012-07-19 15:33:45

2

OrderBy不會修改pprofiles元素的順序,而是它會返回一個新的集合,其中包含元素的順序。你可以試試這個:

pprofiles = pprofiles.OrderBy(x => x.familyName); 

或者你可以使用List(T).Sort

1

您需要分配回你的變量,OrderBy返回分類收集:

pprofiles = pprofiles.OrderBy(x => x.familyName);