如何在LINQ表达式中的多个级别进行排序?

时间:2013-11-04 11:03:36

标签: c# linq

我有以下LINQ表达式:

public IList<Objective> GetObjectives(int examId)
    {
        var objectives = _objectivesRepository
            .GetAll()
            .Where(o => o.ExamId == examId || examId == 0)
            .Include(o => o.ObjectiveDetails)
            .ToList();
        return objectives;
    }

public partial class Objective
{
    public int ObjectiveId { get; set; }
    public int ExamId { get; set; }
    public int Number { get; set; }
    public virtual ICollection<ObjectiveDetail> ObjectiveDetails { get; set; }
}

public partial class ObjectiveDetail
{
    public int ObjectiveDetailId { get; set; }
    public int ObjectiveId { get; set; }
    public int Number { get; set; }
    public string Text { get; set; }
}

如何修改此表达式,以便按Number的顺序返回目标,并按Number的顺序返回ObjectiveDetails?

3 个答案:

答案 0 :(得分:2)

你可以在这里使用投影,例如

var objectives = _objectivesRepository
        .GetAll()
        .Where(o => o.ExamId == examId || examId == 0)
        .Include(o => o.ObjectiveDetails)
        .Select(x => new Objective {
            ObjectiveId = x.Id,
            ExamId = x.ExamId,
            Number = x.Number,
            ObjectiveDetails = x.ObjectiveDetails.OrderBy(d => d.Number).ToList()
        })
        .OrderBy(x => x.Number)
        .ToList();
return objectives;

答案 1 :(得分:2)

public IList<Objective> GetObjectives(int examId)
    {
        var objectives = _objectivesRepository
            .GetAll()
            .Where(o => o.ExamId == examId || examId == 0)
            .Include(o => o.ObjectiveDetails.OrderBy(d => d.Number))
            .OrderBy(o => o.Number);
            .ToList();
        return objectives;
    }

答案 2 :(得分:1)

不幸的是,您必须与主查询分开对嵌套对象进行排序。我不相信有一种方法可以使Include语句按顺序检索元素。

public IList<Objective> GetObjectives(int examId)
{
    var objectives = _objectivesRepository
        .GetAll()
        .Where(o => o.ExamId == examId || examId == 0)
        .Include(o => o.ObjectiveDetails)
        .ToList();
    return objectives.OrderBy(o => o.Number)
        .Select(o => {
            var record = o;
            record.ObjectiveDetails = record.ObjectiveDetails.OrderBy(d => d.Number).ToList();
            return record;
        });
}