157 recommendations for writing high-quality code to improve C # programs--Recommendation 31: Avoid unnecessary iterations in LINQ queries

Source: Internet
Author: User

Recommendation 31: Avoid unnecessary iterations in LINQ queries

Whether it is a SQL query or a LINQ query, it is more efficient to return results immediately than to search all the results and return the results.

Example code:

    classMylist:ienumerable<person>    {        //to demonstrate the need, a collection of elements is simulatedlist<person> list =NewList<person>()            {                NewPerson () {Name ="Mike", age = - },                NewPerson () {Name ="Mike", age = - },                NewPerson () {Name ="Rose", age = - },                NewPerson () {Name ="Steve", age = - },                NewPerson () {Name ="Jessica", age = - }            }; /// <summary>        ///Iteration Count Properties/// </summary>         Public intIteratednum {Get;Set; }  PublicPerson This[inti] {Get{returnlist[i];} Set{ This. list[i] =value;} }        #regionIenumerable<person> Members PublicIenumerator<person>GetEnumerator () {foreach(varIteminchlist) {                //add 1 for each element you traverseiteratednum++; yield returnitem; }        }        #endregion        #regionIEnumerable MembersIEnumerator Ienumerable.getenumerator () {returnGetEnumerator (); }        #endregion    }    classPerson { Public stringName {Get;Set; }  Public intAge {Get;Set; } }

For the above collection, returns the first element with age equal to 20. There are two query modes below, and we'll consider which one is more efficient.

// First Kind var temp = (from inwhereSelect  c). ToList (); // The second Kind var temp2 = (from inwhereSelect c). First ();

Usually we think the first one is more efficient because it seems to return the two elements that are equal to 20, while the second pattern needs to query all elements that are greater than or equal to 20. This is not actually the case. Look at the following test code:

MyList list =NewMyList (); vartemp = ( fromCinchListwhereC.age = = - Selectc).            ToList (); Console.WriteLine (list.            Iteratednum.tostring ()); List. Iteratednum=0; varTemp2 = ( fromCinchListwhereC.age >= - Selectc).            First (); Console.WriteLine (list. Iteratednum.tostring ());

Output:

5

1

Note: The second query iterates only 1 times, because 20 is at the top of the list. The first method actually does the job of searching for a second element that satisfies the condition and returning from the collection. If a collection contains a lot of elements, this kind of query can bring us considerable time efficiency.

Like the first method, the take method receives an integer parameter, and then we return the number specified by the parameter. As with first, it returns directly from the current iteration, rather than waiting for the entire iteration to complete before it satisfies the condition. If a collection contains a lot of elements, then this query will bring us considerable time efficiency.

Note the following example:

MyList list =NewMyList (); vartemp = ( fromCinchListSelectc). Take (2).            ToList (); Console.WriteLine (list.            Iteratednum.tostring ()); List. Iteratednum=0; varTemp2 = ( fromCinchListwhereC.name = ="Mike" Selectc).            ToList (); Console.WriteLine (list. Iteratednum.tostring ());

The output is:

2

5

Although the final result of a LINQ query is to return two element "Mike" objects, in fact, using the Take method only iterates over 2 times for us, while using the where query brings the entire set of iterations.

In the actual coding process, we should make full use of first and take methods to bring efficiency to our application, without wasting time in some invalid iterations.

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 31: Avoid unnecessary iterations in LINQ queries

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.