简体   繁体   English

通过Dynamic Linq订购

[英]OrderBy with Dynamic Linq

I am trying to sort some data from entity before passing them to another function. 我试图从实体中排序一些数据,然后再将它们传递给另一个函数。 Both tableName and columnName are selected dynamically. tableName和columnName都是动态选择的。 This is what I'm doing: 这就是我在做什么:

string tableName = cboSelectTable.Text.ToString();
var comboBoxColumn = from a in Context.RULES where 
                     a.ISCOMBOBOXCOLUMN == "Y" select a.COLUMN;

foreach (var colName in comboBoxColumn)
  {
    var getTableName = entityModel.GetType()
                                  .GetProperty(tableName)
                                  .GetValue(entityModel, null);
    var getData = ((IQueryable<object>)getTableName)
                                      .Where(colName + "!=null")
                                      .Select(colName)
                                      .Distinct()
                                      .OrderBy('"'+ colName +'"');
    dgvCboColumn(getData, colName);
  }

But this is not sorting the data. 但这不是对数据进行排序。 I also tried some other methods too, but couldn't figure it out. 我也尝试了其他方法,但无法解决。 How can I resolve this? 我该如何解决?

I do not think that is the way, .OrderBy(...) works. 我不认为这是.OrderBy(...)工作的方式。 Try ordering by an attribute: 尝试按属性排序:

SomeList.OrderBy(l => l.SomeAttribute);

I suspect ordering by a string results in each element being ordered by the same attribute, thus not ordering at all. 我怀疑按字符串排序会导致每个元素都由相同的属性排序,因此根本不会排序。 In addition, I am not sure, if your where-clause works like that. 另外,我不确定您的子句是否可以那样工作。

There is another relevant SO question already answered. 还有另一个相关的SO问题已经回答。 You might want to have a look at it: click me! 您可能想看看: 点击我!

You can simply place the Select after the OrderBy : 您可以简单地将 Select放置在 OrderBy

 
 
 
 
  
  
  var getData = ((IQueryable<object>)getTableName) .Where(colName + "!=null") .OrderBy(colName) .Select(colName) .Distinct();
 
 
  

This will allow you to reference the column name. 这将允许您引用列名称。 (doesn't seem to work for some reason). (由于某种原因似乎无效)。

Alternatively, you can reference the current instance : 或者,您可以引用当前实例

var getData = ((IQueryable<object>)getTableName)
                  .Where(colName + "!=null")
                  .Select(colName)
                  .Distinct()
                  .OrderBy("it");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM