zoukankan      html  css  js  c++  java
  • List.Select按字符串选择属性

    不知道大家有没有遇到这样的情况: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         }

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

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

  • 相关阅读:
    CSS截取字符串
    mysql数据库中列转行
    Html页面操作json串
    mysql批量上传数据
    常见的表单元素选中
    关于Connection must be valid and open.
    百度editor调用【图片上传阿里云】
    百度apistore第三方登陆
    如何提高网页运行性能
    Html页面加回滚
  • 原文地址:https://www.cnblogs.com/CHWJ2014/p/4257579.html
Copyright © 2011-2022 走看看