157 recommendations for writing high-quality code to improve C # programs--Recommendation 26: Using anonymous types to store LINQ query results

Source: Internet
Author: User

Recommendation 26: Use anonymous types to store LINQ query results

Starting with. NET3.0, C # begins to support a new feature: Anonymous type. An anonymous type consists of a Var, an assignment operator, and a non-null initial value (or an initializer that begins with new). Anonymous types have the following basic features:

    • That is, supporting simple types also indicates complex types. A simple type must be a non-null initial value, and a complex type is an initialization item that begins with new.
    • A property of an anonymous type is read-only and has no property set, and it cannot be changed once it is initialized.
    • If the property values of the two anonymous types are the same, then the two anonymous types are considered equal.
    • An anonymous type can be used as an initializer in a loop.
    • Anonymous types support IntelliSense.
    • Anonymous types can have methods.

Anonymous types are useful in scenarios where the type is only used by the current code or is used to store a query result. Anonymous types are the best partner for saving LINQ query results.

The following scenario:

To take a person or person related class (such as company) out of the database, we need to associate the attribute name in person with the name of the company that corresponds to CompanyID to form a new type. This new type may be used for the binding source of a UI control, perhaps for the input of a particular algorithm. In summary, once the format of the database has been designed and put into use, there will be few changes, but the demand is changing, the actual demand needs to create a lot of such temporary types. If this temporary type all uses normal custom types, the code will swell up and become difficult to maintain. At this point, the anonymous type comes in handy.

    classProgram {Static voidMain (string[] args) {            //to demonstrate the need for companylist not to read from the database, but to assign values directlyList<company> companylist =NewList<company>()            {                NewCompany () {Comanyid =0, Name ="Micro" },                NewCompany () {Comanyid =1, Name ="Sun" }            }; //to demonstrate the need for personlist not to read from the database, but to assign values directlyList<person> personlist =NewList<person>()            {                NewPerson () {Name ="Mike", CompanyID =1 },                NewPerson () {Name ="Rose", CompanyID =0 },                NewPerson () {Name ="Steve", CompanyID =1 }            }; varPersonwithcompanylist = fromPersoninchPersonlist Join Companyinchcompanylist on Person.companyid equals Company.comanyidSelect New{personname = person. Name, CompanyName =Company .            Name}; foreach(varIteminchpersonwithcompanylist) {Console.WriteLine (string. Format ("{0}\t:{1}", item.            PersonName, Item.companyname)); }        }    }    classPerson { Public stringName {Get;Set; }  Public intCompanyID {Get;Set; } }    classCompany { Public intComanyid {Get;Set; }  Public stringName {Get;Set; } }

The output is:

Mike:sun
Rose:micro
Steve:sun

Viewing IL code, you can see that an anonymous type generates a class (also known as a projection) in IL

Non-anonymous types include equals, GetHashcode, ToString, and so on, with anonymous types. And the compiler overloads the ToString method for us, which returns a property of the type that corresponds to the value.

            foreach (var in personwithcompanylist)            {                Console.WriteLine (item. ToString ());            }

The result of the output is:

{personname = Mike, CompanyName = Sun}
{personname = Rose, CompanyName = Micro}
{personname = Steve, CompanyName = Sun}

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 26: Using anonymous types to store LINQ query results

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.