在LINQ中动态访问属性 [英] Access to Properties Dynamically in LINQ

查看:88
本文介绍了在LINQ中动态访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张包含近30个字段的表格.我已经使用LINQ来访问我的数据库.在LINQ中,您可以通过编写如下代码来访问属性:c.propertyname

我现在想做的是,我想在编译时不知道属性名称的情况下访问属性.这意味着将在运行时将属性名称传递给它,因此这意味着我想通过编写类似cX的代码来访问我的属性值(其中X是一个变量,其值将在运行时和动态模式下确定. ).

为此我该怎么办?
提前非常感谢.

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.

推荐答案

您必须在字符串生成器中进行查询,并且必须像下面的示例一样替换运行时
You have to make the query in your string builder and you have to replace it runtime like below example
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();



如果这对您有所帮助,请投票并接受作为答案. :rose:



If this helped you then please Vote and accept as Answer. :rose:


感谢您的回答.似乎会起作用.但是在进行查询之后,我该怎么做才能将已构建的字符串作为(例如)下拉列表的数据源.您知道您不能将字符串作为数据源.那么需要进行什么转换
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


如何在运行时使用C#构建LINQ查询

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


您可以将添加键值对的字典类用于其中,并将其作为数据源绑定到您的下拉列表中,例如
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
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("sb", list);
DropDownList dl = new DropDownList();
dl.DataSource = dict;


这篇关于在LINQ中动态访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆