Use generic list to implement collection classes and sorting functions

Source: Internet
Author: User
1) first define a person classClass person
{
Private int age;

Public int age
{
Get {return age ;}
Set {age = value ;}
}

Public Person (INT age)
{
This. Age = age;
}
}


2) define another personlist collection class, just inherit the list <person>Class personlist: List <person>
{
// Define the sorting method based on the comparison-Defined Signature
Public static int personsort (Person X, person y)
{
If (X. age> Y. Age)
{
Return-1;
}
If (X. age <Y. Age)
{
Return 1;
}
Return 0;
}
}

3) Portal function call

Static void main (string [] ARGs)
{
Personlist plist = new personlist ();
Plist. Add (new person (17 ));
Plist. Add (new person (21 ));
Plist. Add (new person (19 ));
Plist. Add (new person (12 ));

Console. writeline ("Default sequence :");
Foreach (person P in plist)
{
Console. writeline (P. Age );
}

// Define a strongly typed delegate
Comparison <person> sorter = new comparison <person> (personlist. personsort );
Plist. Sort (sorter );

Console. writeline ("Custom sorting :");
Foreach (person P in plist)
{
Console. writeline (P. Age );
}

Console. readkey ();
}


Plus: comparsion <t> This delegate type is used for sorting, and its signature isInt method (T objecta, t objectb)


Summary:
Defining a collection class and some methods in generic mode is indeed more convenient than inheriting from a collectionbase, where you do not need to manually write add () or remove () and so on. If you want the add () method of the Collection class to use an internal access modifier, collectionbase is recommended.

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.