Two ways to find the maximum value in the list

Source: Internet
Author: User

First, ask: Find the object that has the largest value of a property in an object list.

1. Defining objects

1   Private class A 2         {3public             intgetset;} 4 5              Public string Get Set ; } 6         }
2. Define two time period global variables for two methods.

1
privatestaticnew TimeSpan (); 2 Private Static New TimeSpan ();
3. First method: Remove the first object from the list in reverse order of a column.
1         Private Static voidMaxbyorder (list<a>list)2         {3DateTime start =DateTime.Now;4A max = list. OrderByDescending (i =i.id). First ();5TimeSpan span = DateTime.Now-start;6Order + =span;7Console.WriteLine (max. Name +"Order:"+span);8}
4. The second method: first find the maximum value of an attribute in the list, and then take the first object in the list that is equal to the maximum value.
1   Private Static voidMax (list<a>list)2         {3DateTime start =DateTime.Now;4             intMaxid = list. Max (M =m.id);5A max = list. First (i = I.id = =Maxid);6TimeSpan span = DateTime.Now-start;7Compare + =span;8Console.WriteLine (max. Name +"Compare:"+span);9}
5.Main method: Generate a test list and loop through two methods 100 times to print the time spent on each method.
1         Private Static voidMain (string[] args)2         {3list<a> list =NewList<a>();4List = Enumerable.range (1,10000000). Select (n =NewA {ID = n, Name =n.tostring ()}). ToList ();5Console.WriteLine ("Print");6             inti =0;7              while(I < -)8             {9 Maxbyorder (list);Ten Max (list); Onei++; A             } -Console.WriteLine ("Compare:"+Compare); -Console.WriteLine ("Order:"+order); the console.readline (); -}

6. View the results of the operation:

The first two ways to find the maximum value, the first way to basically spend time for the second kind of four to five times times.

OK, this is the first day, I hope you will shoot bricks ...

Two ways to find the maximum value in the list

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.