OrderBy with Dynamic Linq

c# dynamic-linq entity-framework winforms

Question

I am trying to sort some data from entity before passing them to another function. Both tableName and columnName are selected dynamically. 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?

1
0
9/22/2017 9:50:00 AM

Accepted Answer

You can simply place the Select after the 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");
0
2/4/2015 11:50:58 AM

Popular Answer

I do not think that is the way, .OrderBy(...) works. 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. You might want to have a look at it: click me!



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow