List. Select select Properties by string, list. Select string
I wonder if you have encountered such a situation: when using Lambda expressions in List, you want to select an attribute column of an item.
For example, select the ID:
1 var idList=list.Select(o=>o.ID).ToList();
Also, you want to select a name:
1 var nameList=list.Select(o=>o.Name).ToList();
Can it be abstracted? The following is my method.
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 (); // the conversion can be processed by yourself. For simplicity. 13} 14} 15} 16 return TResult; 17}
Input and Output types can be input during the call.
The above is my imagination. If you have a better way, please contact us.