Click here to Skip to main content
15,911,531 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table with almost 30 fields. I have used LINQ in order to access to my DB. In LINQ you can access to properties by writing a code like this: c.propertyname

What I want now to do is that I want to access the properties without knowing the property name at compile time. It means that the property name will be passed to at runtime, so it means that I want to access my property value by writing a code like c.X (in which X is a VARIABLE that its value will be determined during runtime and in a dynamic mode).

What can I do in order to that?
Thanks a lot in advance.
Posted

You have to make the query in your string builder and you have to replace it runtime like below example
C#
StringBuilder sb = new StringBuilder();
string runtimePropertyName = string.Empty;
string runtimePropertyValue = string.Empty;
sb.Append("from a in db.abc where a.#PropertyName#==#PropertyValue# select a.ToList();");
sb.Replace("#PropertyName#", runtimePropertyName);
sb.Replace("#PropertyValue#", runtimePropertyValue);
var list = sb.ToString();


If this helped you then please Vote and accept as Answer. :rose:
 
Share this answer
 
Comments
Hiren solanki 2-Nov-10 3:10am    
are you sure it will run ?
Dalek Dave 2-Nov-10 4:22am    
Good Answer.
Xmindz 13-Mar-12 1:43am    
Did this one work?
Xmindz 13-Mar-12 1:46am    
Can we do something similar with the LINQ predicates? Like .OrderBy(x=> x.PropertyName)
Can I change the PropertyName dynamically here?
thanks for your answer. it seems that will work. but after making the query, what can i do in order to put the string that has been built as the datasourse of a (for example) dropdownlist. you know that you can not put a string as the datasourse. so what is the conversion that is needed
 
Share this answer
 
How to build LINQ Queries at Runtime in C#

http://tomasp.net/blog/dynamic-linq-queries.aspx[^]


You can use the dictionary class for that add key-value pair into it and bind as the datasource to your dropdown list like
C#
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("sb", list);
DropDownList dl = new DropDownList();
dl.DataSource = dict;
 
Share this answer
 
v2

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