Alborz
Alborz

Reputation: 6903

How to alias a column name in LINQ at runtime?

I have a list of objects:

List<MyClass> list = new List<MyClass>();

And this is my query

var q = from o in list
      select new
      {
        column1 = o.X
      };

This works but I want to set column1 at runtime as follows:

string column1 = "myColumnName";
var q = from o in list
    select new
    {
       column1 = o.X 
    };

How do I do that?

Upvotes: 2

Views: 2772

Answers (1)

Grundy
Grundy

Reputation: 13381

As i understand from your comment you need not alias for column at runtime, you need something like this

string columnName = "myColumnName";
var q = from o in list
        select new KeyValuePair<string,string>(columnName,o.X);

and bind this to combobox like this

comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
comboBox.DataSource = q;
comboBox.DataBind();

Upvotes: 1

Related Questions