我无法对我传递给视图的用户个人资料列表进行排序。我想显示某个角色中所有用户的列表,我想按familyName属性对它们进行排序。
我尝试使用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>
我需要在多个地方重复使用它,并且可能会有大量用户,所以不要在某种程度上订购它们会很糟糕。我该怎么办呢?
答案 0 :(得分:2)
OrderBy不会修改pprofiles
元素的顺序,而是返回包含已排序元素的新集合。你可以试试这个:
pprofiles = pprofiles.OrderBy(x => x.familyName);
或者您可以使用List(T).Sort
答案 1 :(得分: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);
答案 2 :(得分:1)
您需要将其分配回您的变量,OrderBy
返回已排序的集合:
pprofiles = pprofiles.OrderBy(x => x.familyName);