List. Select select Properties by string, list. Select string

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.