Use more effective objects and set Initialization

Source: Internet
Author: User

This suggestion should be known or used by many people. If you do not know it, you will be out. List <Person> list = new List <Person> (); Person p = new Person (); p. ID = 1; p. name = "Tommy"; list. add (p); Sao Nian, are you still doing object and set initialization like this? With the help of the advanced. NET syntax, we can use the object and set initialization tool to write more elegant code. Set the attribute value in braces List <Person> lst = new List <Person> () {new Person () {ID = 1, Name = "Tommy "}, new Person () {ID = 2, Name = "Sammy"}; except for the convenience of object and set initialization, it is also convenient to initialize attributes for the anonymous type during the Linq query. Copy the code List <Person> lst = new List <Person> () {new Person () {Age = 10, Name = "Tommy"}, new Person () {Age = 20, Name = "Sammy" }}; var entity = from p in lst select new {p. name, Agoda = p. age> 10? "Old": "Young"}; foreach (var item in entity) {Response. write (string. format ("name is {0}, {1}", item. name, item. agoda);} copying the Agoda attribute of the Code is calculated. With this convenient initialization method, the code is more elegant and flexible.

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.