157 recommendations for writing high-quality code to improve C # programs--recommendation 10: Consider whether to implement a comparer when creating objects

Source: Internet
Author: User

Recommendation 10: Consider whether to implement a comparer when creating objects

There are comparisons where objects exist, as in the world of. Net. For the simplest example, there is a salary list of 10 people in the UI. Depending on the sort needs, the list supports salary for base pay. At this point, the interface IComparable will work, and the code looks like this:

    classsalary:icomparable { Public stringName {Get;Set; }  Public intbasesalary {Get;Set; }  Public intBonus {Get;Set; } #regionIComparable Members Public intCompareTo (Objectobj) {Salary Staff= obj asSalary; if(Basesalary >Staff . Basesalary) {return 1; }              Else if(Basesalary = =Staff . Basesalary) {return 0; }              Else              {                  return-1; }              //return Basesalary.compareto (staff.  Basesalary);         }               #endregion      } 

Note that the CompareTo method in the above code has a commented code, in fact this method can be used instead of the comment code, because the use of the default comparison method of the integer type. This comment code is not used here to better illustrate how the comparator works.

Once the interface IComparable is implemented, we can sort the salary according to Basesalary, as shown in the following code:

ArrayList companysalary =NewArrayList (); Companysalary.add (NewSalary () {Name ="Mike", basesalary = the }); Companysalary.add (NewSalary () {Name ="Rose", basesalary = - }); Companysalary.add (NewSalary () {Name ="Jeffry", basesalary = + }); Companysalary.add (NewSalary () {Name ="Steve", basesalary =4000 });      Companysalary.sort (); foreach(Salary Iteminchcompanysalary) {Console.WriteLine (item. Name+"\ t basesalary:"+item.      Basesalary.tostring ()); } 

The output of the above code is as follows:

    Jeffry-         Rose     ,      Mike             Steve    4000

Now, the question is: What if you don't want to sort by the base pay basesalary, but instead use the bonus bonus to sort it out? This time, the role of interface IComparer is reflected, you can use IComparer to implement a custom comparator. As shown below:

    class Bonuscomparer:icomparer      {          #region IComparer members                Public int Compare (objectobject  y)          {              as  Salary;                as Salary;               return s1.Bonus.CompareTo (S2. Bonus);          }                #endregion      

We provide this comparer for the sort method when sorting, as shown in the code below:

ArrayList companysalary =NewArrayList (); Companysalary.add (NewSalary () {Name ="Mike", basesalary = the, Bonus= + }); Companysalary.add (NewSalary () {Name ="Rose", basesalary = -, Bonus=4000 }); Companysalary.add (NewSalary () {Name ="Jeffry", basesalary = +, Bonus=6000 }); Companysalary.add (NewSalary () {Name ="Steve", basesalary =4000, Bonus= the }); Companysalary.sort (NewBonuscomparer ());//providea non-default comparer    foreach(Salary Iteminchcompanysalary) {Console.WriteLine (string. Format ("name:{0} \tbasesalary:{1} \tbonus:{2}", item. Name, item. Basesalary, item.      Bonus)); } 

The output results are as follows:

    Name:mike       basesalary:         Bonus:      name:steve      basesalary:  4000         Bonus:      name:rose       basesalary:         Bonus: 4000       name:jeffry     basesalary:         Bonus:6000

If we have a little experience, we will find that the above code uses a collection class ArrayList that has not been recommended (when generics come out, it is recommended that you try not to use all non-generic collection classes). As for the reasons, we can also see the clues from the above code. Note See the Compare function in the code, such as:

     Public int Compare (objectobject  y)      {          as  Salary;            as Salary;           return s1.Bonus.CompareTo (S2. Bonus);      

We have found that this function has been transformed, which can affect performance. If there are thousands of complex entity objects in the collection, the performance that is consumed when sorting is considerable, and generics can avoid the runtime transformation. Therefore, the above code in the ArrayList, should be replaced by a list, corresponding to, we should implement IComparable and IComparer. The final code should look like this:

         classSalary:icomparable<salary>     {           Public stringName {Get;Set; }  Public intbasesalary {Get;Set; }  Public intBonus {Get;Set; } #regionIcomparable<salary> Members Public intCompareTo (Salary other) {returnBasesalary.compareto (Other.          Basesalary); }               #endregion      }           classBonuscomparer:icomparer<salary>     {          #regionIcomparer<salary> Members Public intCompare (Salary x, Salary y) {returnX.bonus.compareto (Y.bonus); }                #endregion      }    Static voidMain (string[] args) {List<Salary> companysalary =NewList<salary>()              {                  NewSalary () {Name ="Mike", basesalary = the, Bonus = + },                  NewSalary () {Name ="Rose", basesalary = -, Bonus =4000 },                  NewSalary () {Name ="Jeffry", basesalary = +, Bonus =6000 },                  NewSalary () {Name ="Steve", basesalary =4000, Bonus = the }              }; Companysalary.sort (NewBonuscomparer ());//provides a non-default comparer        foreach(Salary Iteminchcompanysalary) {Console.WriteLine (string. Format ("name:{0} \tbasesalary:{1} \tbonus:{2}", item. Name, item. Basesalary, item.          Bonus)); }      }  

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 10: Consider whether to implement a comparer when creating objects

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.