在控制器中排序结果

Ordering the results in a controller

我的控制器中有以下操作:

public ActionResult Details(String id)
{
    MyRecordContext rc = new MyRecordContext();
    List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id).ToList();

    return View(rl);
}

如何将 order by 子句添加到我的查询中以对 x.RecordName 字段上的记录进行排序?

您可以使用 OrderBy 扩展方法,例如

public ActionResult Details(String id)
{
    MyRecordContext rc = new MyRecordContext();
    List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id).OrderBy(x => x.RecordName).ToList();

    return View(rl);
}

这将按 RecordName 字母顺序排列项目。

您可以对 eg

使用 OrderBy
public ActionResult Details(String id)
{
MyRecordContext rc = new MyRecordContext();
List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id).OrderBy(x => x.RecordName ).ToList();
return View(rl);
}

如果你想按两个字段排序,你可以这样做:

List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id)
                                .OrderBy(r=>r.RecordName)
                                .ThenBy(r=>r.RecordTitle)
                                .ToList();

ThenBy 方法根据您多次调用 OrderBy 的 key.If 对序列中的元素按升序进行后续排序,它将有效地对序列完全重新排序两次次