1

我有以下 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返回 ObjectiveDetails Number

4

3 回答 3

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;
于 2013-11-04T11:10:28.933 回答
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;
    }
于 2013-11-04T11:10:57.183 回答
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;
        });
}
于 2013-11-04T11:28:19.477 回答