0

我在对传递给视图的用户配置文件列表进行排序时遇到问题。我想显示某个角色的所有用户的列表,并且我想按 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>

我需要在多个地方重复使用它,并且可能有大量用户,所以不以某种方式订购它们会很糟糕。我该怎么办?

4

3 回答 3

2

OrderBy 不修改pprofiles元素的顺序,而是返回一个新的集合,其中的元素是有序的。你可以试试这个:

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

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

于 2012-07-19T15:18:53.437 回答
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);
于 2012-07-19T15:19:56.757 回答
1

您需要将其分配回您的变量,OrderBy返回排序集合:

pprofiles = pprofiles.OrderBy(x => x.familyName);
于 2012-07-19T15:19:15.853 回答