Object comparison and sorting (7): sorting and searching generic lists: applications of comparison and predicate

Source: Internet
Author: User

As mentioned above, we can use the icomparer <t> and icomparable <t> interfaces to compare two objects and then sort the list of objects of this type. Now we will introduce the other two delegates that can be used to sort and search the list.

First, summarize the previous content:

On msdn, list has the following sort overload:

If you call the sort () method without parameters, the elements in the set must implement the system. icomparable interface. Otherwise, an invalidoperationexception is thrown.

If the element of the set does not implement the icomparable interface, you can call sort (icomparer <t>). In this case, we need to create a class to implement the icomparer interface as the comparator to complete the sorting.

Or it is simpler. You don't need to define a comparator. simply provide a method for the sort method to "compare two objects"-implement comparison <t> delegation.

See another diary:

Http://www.cnblogs.com/eagle1986/archive/2012/02/07/2341719.html

 

Generally, a method is required to sort the list to compare two T-type objects. To search in the list, you also need a method to check T-type objects to see if they meet a certain condition. Defining this method is simple. Here we provide two generic delegation that can be used.

1. comparision <t> This delegate type is used for sorting methods. The return type and parameter are int method (t object A, T objectb)

2. predicate <t> This delegate type is used to search for methods. The return type and parameter are bool method (T targetobject ).

You can define any of these methods and use them to implement the list <t> Search and sorting methods.

 

 

Define a Vector class

Vector

 Public   Class Vector
{
Public Double ? R = Null ;
Public Double ? Theta =Null ;

Public Double ? Thetaradians
{
Get
{
// Convert degrees to radians.
Return (Theta * Math. PI/ 180.0 );
}
}

Public Vector (Double ? R, Double ? Theta)
{
// Normalize.
If (R < 0 )
{
R =-R;
Theta + = 180 ;
}
Theta = Theta % 360 ;

// Assign fields.
R = R;
Theta = Theta;
}

Public Static Vector Operator + (Vector OP1, vector OP2)
{
Try
{
// Get (x, y) coordinates for new vector.
Double Newx = op1.r. Value * Math. Sin (op1.thetaradians. value)
+ Op2.r. Value * Math. Sin (op2.thetaradians. value );
Double Newy = op1.r. Value * Math. Cos (op1.thetaradians. value)
+ Op2.r. Value * Math. Cos (op2.thetaradians. value );

// Convert to (R, theta ).
Double Newr = math. SQRT (newx * newx + newy * newy );
Double Newtheta = math. atan2 (newx, newy )* 180.0 /Math. Pi;

// Return result.
Return New Vector (newr, newtheta );
}
Catch
{
// Return "null" vector.
Return New Vector ( Null ,Null );
}
}

Public Static Vector Operator -(Vector OP1)
{
Return New Vector (-op1.r, op1.theta );
}

Public Static Vector Operator -(Vector OP1, vector OP2)
{
Return OP1 + (-OP2 );
}

Public Override String Tostring ()
{
// Get string representation of coordinates.
String Rstring = R. hasvalue? R. tostring (): " Null " ;
String Thetastring = Theta. hasvalue? Theta. tostring (): " Null " ;

// Return (R, theta) string.
Return String . Format ( " ({0}, {1 }) " , Rstring, thetastring );
}
}

 

The following defines a collection class Vectors

Collection class

     Public   Class Vectors: List <vector>
{
Public Vectors ()
{
}

Public Vectors (ienumerable <vector> initialitems)
{
Foreach (Vector Vector In Initialitems)
{
Add (vector );
}
}

Public String Sum ()
{
Stringbuilder sb = New Stringbuilder ();
Vector currentpoint = New Vector ( 0.0 , 0.0 );
SB. append ( " Origin " );
Foreach (Vector Vector In This )
{
SB. appendformat ( " + {0} " , Vector );
Currentpoint + = vector;
}
SB. appendformat ( " = {0} " , Currentpoint );
Return SB. tostring ();
}
}

 

 

 

The following is the method we want to define for sorting and searching.

View code

     Public   Static   Class Vectordelegates
{
Public Static Int Compare (vector X, vector y)
{
If (X. r> Y. R)
{
Return 1 ;
}
Else If (X. r <Y. R)
{
Return - 1 ;
}
Return 0 ;
}

Public Static Bool Toprightquadrant (vector target)
{
If (Target. Theta> = 0.0 & Amp; target. Theta <= 90.0 )
{
Return True ;
}
Else
{
Return False ;
}
}
}

The aboveCode, Compare for comparison, and toprightquadrant for search.

 

The following is the test code.

Test code

  Class Program
{
Static Void Main ( String [] ARGs)
{
Vectors route = New Vectors ();
Route. Add ( New Vector ( 2.0 ,90.0 ));
Route. Add ( New Vector ( 1.0 , 180.0 ));
Route. Add ( New Vector ( 0.5 , 45.0 ));
Route. Add ( New Vector ( 2.5 , 315.0 ));

Console. writeline (route. sum ());

Comparison <vector> sorter = New Comparison <vector> (vectordelegates. Compare );
Route. Sort (sorter );
Console. writeline (route. sum ());

Predicate <vector> searcher =
New Predicate <vector> (vectordelegates. toprightquadrant );
Vectors toprightquadrantroute = New Vectors (route. findall (Searcher ));
Console. writeline (toprightquadrantroute. sum ());

Console. readkey ();
}
}

Summary:

1. For more information about predicate <t> usage, see http://www.cnblogs.com/eagle1986/archive/2012/01/19/2327351.html

2. You can refer to the previous diary and use Lamda expressions to make the code more concise.

 

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.