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         }

調用時傳入輸入、輸出類型即可。

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM