Nezir
Nezir

Reputation: 6905

Linq using variable as column name in select new statement

I have a LINQ query and as you can see I am trying to use variables as column names.

string first = "someColumnName1";
string sec = "someColumnName2";
string third = "someColumnName3";

var data = (from i in ctx.PlanskaKalkulacijas
            where i.PKid.Value == id
            select new { first = i.NP1, sec = i.NP2, third = i.NP3}
           ).OrderByDescending(m => m.Id)
            .ToList();

this code produce column names in gridview as first, sec and third but I need someColumnName1, someColumnName2, someColumnName3.

Any help ?

Upvotes: 2

Views: 5117

Answers (1)

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

Either rename columns in the gridview after you insert data or name properties of the anonymous type you create properly.

var data = (from i in ctx.PlanskaKalkulacijas 
            where i.PKid.Value == id 
            select new 
            { 
                someColumnName1 = i.NP1, 
                someColumnName2 = i.NP2, 
                someColumnName3 = i.NP3
            }).OrderByDescending(m => m.Id)
              .ToList();

If you don't know values at compile time, just rename it. To do that, follow this question here on SO.

Upvotes: 3

Related Questions