对mvc3中的UserProfiles列表进行排序asp.net应用程序
问题描述:
我在排序传递给视图的用户配置文件列表时遇到问题。我想要显示某个角色中所有用户的列表,并且我想通过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>
我需要在多个地方重新使用这一点,可能有大量的用户,以便在没有命令他们有时候会很糟糕。我应该怎么做呢?
答
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);
答
OrderBy不会修改pprofiles
元素的顺序,而是它会返回一个新的集合,其中包含元素的顺序。你可以试试这个:
pprofiles = pprofiles.OrderBy(x => x.familyName);
或者你可以使用List(T).Sort
答
您需要分配回你的变量,OrderBy
返回分类收集:
pprofiles = pprofiles.OrderBy(x => x.familyName);
更确切地说'OrderBy'将返回一个'IOrderedEnumerable' –
Zbigniew
2012-07-19 15:20:44
啊,很好!我去Linq风格的方式,它像一个魅力。谢谢!你能否详细解释它是如何工作的?我在猜测选择遍历用户列表并获取他们的配置文件......或者它是否将返回的用户列表更改为UserProfiles列表? – Nieszka 2012-07-19 15:33:45