Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
Hi,
I want to pass a string variable as column name in linq. how is it possible? i am using the following code but its not working.
C#
string colName="Ditrict";
var districtlist = db.table1.Select(colName).Distinct().ToList();


I shall be thankful for your help.
Posted
Updated 22-Sep-13 0:33am
v2

1 solution

You can try like below :

C#
var districtlist = db.table1.Select(d=>new {Ditrict=d.Ditrict}).Distinct().ToList();


UPDATE

C#
string colName="Ditrict";
var districtlist = db.table1.Select(d=>new {d.colName}).Distinct().ToList();



For more info check this Method based Query syntax Article:

http://msdn.microsoft.com/en-us/library/bb896310.aspx[^]

UPDATE 2

You may try with Dynamic LINQ :
For more info check this :

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx[^]


I hope this will help to you.
 
Share this answer
 
v5
Comments
osama.javed 22-Sep-13 6:40am    
Thankyou sir, But the name of column is dynamic, it'll not always be district. I need to select the column passed in string variable.
Sampath Lokuge 22-Sep-13 6:46am    
Plz check my "UPDATE' section.
osama.javed 22-Sep-13 6:54am    
Sir, Its still not working... :( Error
Sampath Lokuge 22-Sep-13 7:05am    
Plz,check my "UPDATE 2" section.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900