有没有一种简单的方法,以对象的属性转换为字典<字符串,字符串> [英] Is there an easy way to convert object properties to a dictionary<string, string>

查看:181
本文介绍了有没有一种简单的方法,以对象的属性转换为字典<字符串,字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数据库表,我有很多领域的(ASP:文本框,ASP:DropDownList的等)的,我想变成一本字典的地图,让我可以循环通过并将它们添加到表单字段。

Say I have a database table, that I have a lot of fields (asp:textbox, asp:dropdownlist etc), that I want to turn into a dictionary map, so that I can loop through and add them to the form fields.

例如:

Dictionary<string, string> FD = new Dictionary<string,string>();
FD["name"] = data.name;
FD["age"] = data.age;
FD["occupation"] = data.occupation;
FD["email"] = data.email;
..........

这样我就可以通过FD词典循环,并添加控件在页面上。

This way I can loop through FD dictionary, and add to Controls on the page.

我怎么会做这个很容易,无需打字数据库元素和字典元素的所有各种100S。

How would I do this easily, without typing out all the various 100s of database elements and dictionary elements.

注:FD字典指标是相同的数据库列名

Note: FD dictionary indices are same as database column names.

(在一个侧面说明,这是安全的呢?从本质上讲一些检查可能需要使用户不能使自己的表单元素,如NAME ='ID',并提交,并且该脚本将之类的东西ID的数据库。我使用实体框架,所以我不认为注入是一个问题。)

(On a side note, is this safe to do? Essentially some checks may be required so that users cannot make their own form elements like "name='id'" and submit, and the script adds things like ID to the database. I use entity framework so I don't think injection is a problem.)

编辑:纳秒算法的效率速度测试:

首先算法(开机-X ):<击> 7000700 nanoseconds0.01 seconds0.00分钟 - 8000800纳秒

First algorithm (Splash-X): 7,000,700 nanoseconds0.01 seconds0.00 minutes -- 8,000,800 nanoseconds

二算法( L.B ):3000300 nanoseconds0.00 seconds0.00分钟(不与NULL值工作)

Second algorithm (L.B): 3,000,300 nanoseconds0.00 seconds0.00 minutes (doesn't work with NULL values)

第三算法(叶海亚):<击> 29002900 nanoseconds0.03 seconds0.00分钟 - 2000200 纳秒

Third algorithm (Yahia): 29,002,900 nanoseconds0.03 seconds0.00 minutes -- 2,000,200 nanoseconds

推荐答案

假设数据一些对象,你想要把它的公共属性成一个字典,然后尝试

Assuming that data is some object and that you want to put its public properties into a Dictionary then try

Dictionary<string,string> FD = (from x in data.GetType().GetProperties() select x).ToDictionary ( x => x.Name, x => (x.GetGetMethod().Invoke (data, null) == null ? "" : x.GetGetMethod().Invoke (data, null).ToString()));

请注意:本使用反射,因此是不是真的快...

BEWARE: this uses reflection and thus is not really fast...

这篇关于有没有一种简单的方法,以对象的属性转换为字典&LT;字符串,字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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