List.Select按字符串选择属性

摘要:
在列表中使用lambda表达式时,1varnameList=List。选择(o=>=null&&0)5{6varproperties=TSource[0].GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflecton.BindingFlags.Instance);

不知道大家有没有遇到这样的情况:List使用Lambda表达式的时候,想要选择项的某个属性列。

例如,选择编号ID:

1 var idList=list.Select(o=>o.ID).ToList();

又,想要选择名称:

1 var nameList=list.Select(o=>o.Name).ToList();

可否将其抽象呢?下面是我的方法。

 1         public List<TR> GetProperty<TS, TR>(List<TS> TSource, string propertyName)
 2         {
 3             List<TR> TResult = null;
 4             if (TSource != null && TSource.Count > 0)
 5             {
 6                 var properties = TSource[0].GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
 7                 if (properties != null)
 8                 {
 9                     System.Reflection.PropertyInfo property = properties.FirstOrDefault(o => o.Name == propertyName);
10                     if (property != null)
11                     {
12                         TResult = TSource.Select(o => (TR)property.GetValue(o, null)).ToList(); //转换可自行处理。此处为了简单起见。
13                     }
14                 }
15             }
16             return TResult;
17         }

调用时传入输入、输出类型即可。

以上是本人臆想,如有更好方式,欢迎交流。

免责声明:文章转载自《List.Select按字符串选择属性》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Spring+SpringMVC+MyBatis深入学习及搭建(八)——MyBatis查询缓存Oracle 和SQL Server 中的SQL语句使用区别下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

利用span设置文字固定宽度

<input type="radio" name="dispMode" value="manul"/><label for="rdoManul"><span class="modeText">手动下载</span></label> <input type=...

Vue-es6语法

一、Vue课程介绍 二、es6中的let和const声明变量 三、es6中的模板字符串 四、es6的箭头函数(函数的书写) 五、对象的单体模式 六、es6中的class的使用 七、前端三大框架比较 八、前端框架与库的区别 九、nodejs中npm的使用 一、Vue课程介绍 1)上来先不要搞Vue,因为前端知识太多,html+css+js(ECMAScri...

用友GRP-u8 XXE 漏洞复现

0x00 漏洞描述  用友GRP-u8存在XXE漏洞,该漏洞源于应用程序解析XML输入时没有进制外部实体的加载,导致可加载恶意外部文件。 0x01 漏洞利用条件 无需登录 0x02 漏洞复现 POC: POST /Proxy HTTP/1.1 Content-Type: application/x-www-form-urlencoded User-Age...

小程序换行符检测换行

先将换行符替换成自定义连接字符 var goods_detail = "" if(res.data.info.goods_info.goods_detail){ goods_detail = res.data.info.goods_info.goods_detail; var str=goods_detail.replace(/ /g,"|-&")...

高德地图API,地图类型切换(卫星地图)

常用控件 AMap.MapType :地图类型切换插件,可用于切换卫星地图 首先记得引入插件 <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=ce3b1a3a7e67fc75810ce1ba1f83c01a&plugin=AMa...

写了个用jquery控制select只读(select选项可以供用户查看但不能改变初始选中值)

转载自: http://www.cnblogs.com/case/articles/1864500.html <scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> &...