动态LINQ OrderBy用于在C#中使用Expression的导航属性

时间:2017-05-22 14:22:46

标签: c# linq sorting linq-to-sql iqueryable

我有两张桌子,即学生和马克

表:DbSet<StudentInfo>

ID    Name
_____________________
1     Ram
2     Kumar
3     John

表:DbSet<ScoreInfo>

Id    StudentId    Subject    Score
_____________________________________
1     1            GK         90
2     1            SCI        97
3     2            GK         81
4     2            SCI        99

LINQ to SQL返回以下列表

StudentId    Name    Subject    Score  
_____________________________________
1            Ram    GK         90
1            Ram    SCI        97
2            Kumar  GK         81
2            Kumar  SCI        99
3            John   null       null

C#代码是

using(var db = new StudentEntity()) {
    var query = db.Student.Where(m => true);

    Expression<Func<StudentInfo,object>> sortExpression = null;

    if(sortColumn == "Name") {
        sortExpression = i => i.Name
    } else if(sortColumn == "Subject") {
        // ? How to achieve this
    }

    query = isAcending
                ? query.OrderBy(sortExpression)
                : query.OrderByDescending(sortExpression);

    query.Select(m => (...)).Dump();
}

变量sortColumnString,它指定列需要排序,变量isAcendingbool,它指定排序方向。

我需要对Subject列进行排序。请帮助我如何撰写Expression<Func<StudentInfo,object>>,查询应该是IQueryable

2 个答案:

答案 0 :(得分:2)

正是你写lambda的方式:

Expression<Func<StudentInfo,object>> sortExpression = si=>si.Name;

(请注意,您不能在那里使用var,因为编译器需要知道您希望它为Expression<T>

但您真正的问题是您正在尝试使用尚未创建的StudentInfo对象。首先你创建一个,然后按它排序;

 db.Mark.Select(m=> new StudentInfo {
                    StudentID = m.StudentId, 
                    Name = m.Student.Name,
                    Subject = m.Subject,
                    Score = m.Score});

Expression<Func<StudentInfo, object>> sortExpression = null;

if (sortColumn == "Name")
{
    sortExpression = i => i.Name;

}
else if (sortColumn == "Subject")
{
    sortExpression = i => i.Subject;
}

    query = isAcending
                ? query.OrderBy(sortExpression)
                : query.OrderByDescending(sortExpression);

    return query;

答案 1 :(得分:0)

您可以将字符串传递给OrderBy方法,

之类的东西

"colName ASC, anotherCol Desc, etc..."

你可以做这样的事情,

string orderstring = sortColumnName +" "+ (isAcending ?? "ASC" : "DESC"); query = query.OrderBy(orderstring);