【问题标题】:Replacing my current Linq OrderBy with Dynamic Linq用动态 Linq 替换我当前的 Linq OrderBy
【发布时间】:2015-10-02 05:08:34
【问题描述】:

我的操作方法中有以下代码来 OrderBy 我的数据:-

if (String.IsNullOrEmpty(sort))
{
    vm = repository.FindVMs(withOutSpace).OrderBy(a => a.Technology.PartialSerial).ToPagedList(page, pagesize);
}
else if(sort == "server_desc")
{
    vm = repository.FindVMs(withOutSpace).OrderByDescending(a => a.ITServer.Technology.PartialSerial).ToPagedList(page, pagesize);
    ViewBag.ServerSortPam = "server_ans";
}
else 
{
    vm = repository.FindVMs(withOutSpace).OrderBy(a => a.ITServer.Technology.PartialSerial).ToPagedList(page, pagesize);
    ViewBag.ServerSortPam = "server_desc";
}

我已经安装了Linq.Dynamics,但我不确定如何替换我当前的代码来使用动态 linq 查询,这样我就不必为不同的排序参数手动编写单独的 orderBY 语句。?

主要是为了让“OrderByDescending(a => a.ITServer.Technology.PartialSerial)”&“OrderBy(a => a.ITServer.Technology.PartialSerial)”根据传入的参数动态生成,而不用写两个不同的linq查询?

谢谢

【问题讨论】:

    标签: asp.net-mvc linq asp.net-mvc-4


    【解决方案1】:

    OrderBy 和 OrderByDecending 子句使用动态 linq 看起来像这样:

    OrderBy("ITServer.Technology.PartialSerial")
    

    OrderBy("ITServer.Technology.PartialSerial DESC").
    

    如果您想摆脱额外的 if 语句,传递标志而不是字符串值可能会有所帮助。例如:

    IQueryable<SomeEntityType> ApplySort(IQueryable<SomeEntityType> query, bool? sortByPartialAsc)
    {
        var sb = new StringBuilder();
    
        sb.Append("ITServer.Technology.PartialSerial");
    
        if (sortByPartialAsc == false) sb.Append(" DESC");
    
        return query.OrderBy(sb.ToString());
    }
    

    根据您的视图模型如何生成排序参数,此方法可能需要一些调整,但您应该明白这一点。

    如果您有兴趣,我一直在更新 Dynamic Linq。 https://github.com/NArnott/System.Linq.Dynamic

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多