Paradox
Paradox

Reputation: 129

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. 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?

Upvotes: 0

Views: 147

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51430

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");

Upvotes: 0

Nephtyz
Nephtyz

Reputation: 103

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!

Upvotes: 1

Related Questions