. NET Framework System. Array. Sort demo, array. sort

Source: Internet
Author: User

. NET Framework System. Array. Sort demo, array. sort
Content

  • Custom class
  • Array. Sort
  • References
 

System. Array. Sort has many set operations, such as sorting, searching, and cloning. You can use this class to deepenIComparer, IComparableUnderstanding of generic delegation, anonymous methods, and Lambda expressions.

Download Demo custom class

Two custom classes:PersonAndPersonComparer. These two classes will be used later.

CustomPersonClass, which has two attributes:FirstNameAndLastName, RestructuredToStringMethod. This class also inheritsIComparableInterface to implementCompareToMethod.Array. SortMethod. As follows:

public class Person : IComparable
{
    public Person()
    {
 
    }
 
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
 
    public string FirstName { get; set; }
 
    public string LastName { get; set; }
 
    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
 
    public int CompareTo(object obj)
    {
        Person other = obj as Person;
        return this.LastName.CompareTo(other.LastName);
    }
}

Note:CompareToBy defaultLastNameComparison.

CustomPersonComparerClass, this class defines a comparison type, you can pressFirstNameOrLastNameComparison.PersonComparerClass inheritanceIComparerThe Compare methods of interfaces are implemented in non-generic and generic forms.Array. SortUsed in. As follows:

public class PersonComparer : IComparer, IComparer<Person>
{
    public enum PersonCompareType
    {
        FirstName,
        LastName
    }
 
    private PersonCompareType compareType;
 
    public PersonComparer(PersonCompareType compareType)
    {
        this.compareType = compareType;
    }
 
    public int Compare(object x, object y)
    {
        Person p1 = x as Person;
        Person p2 = y as Person;
        switch (compareType)
        {
            case PersonCompareType.FirstName:
                return p1.FirstName.CompareTo(p2.FirstName);
            case PersonCompareType.LastName:
                return p1.LastName.CompareTo(p2.LastName);
            default:
                throw new ArgumentException("unexpected compare type");
        }
    }
    public int Compare(Person x, Person y)
    {
        Person p1 = x;
        Person p2 = y;
        switch (compareType)
        {
            case PersonCompareType.FirstName:
                return p1.FirstName.CompareTo(p2.FirstName);
            case PersonCompareType.LastName:
                return p1.LastName.CompareTo(p2.LastName);
            default:
                throw new ArgumentException("unexpected compare type");
        }
    }
}
Array. Sort

Array. Sort has 17 "reloads", as shown below:

Sort(Array)      
Sort(Array, Array)      
Sort(Array, IComparer)      
Sort(Array, Array, IComparer)      
Sort(Array, Int32, Int32)      
Sort(Array, Array, Int32, Int32)       
Sort(Array, Int32, Int32, IComparer)      
Sort(Array, Array, Int32, Int32, IComparer)         
Sort<T>(T[])       
Sort<T>(T[], IComparer<T>)      
Sort<T>(T[], Comparison<T>)      
Sort<T>(T[], Int32, Int32)       
Sort<T>(T[], Int32, Int32, IComparer<T>)      
Sort<TKey, TValue>(TKey[], TValue[])        
Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>)        
Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32)        
Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)

From their parameters, You can first imagine:

  • These methods can be divided into non-generic form and generic form, that is, each non-generic form basically corresponds to a generic form;
  • If we want to sort a set, it must be compared, and the default value is ascending;
  • If the set is a string, it is easy to do and almost no need to do anything;
  • If the set is an object, we must specify how to compare and compare two objects;
  • If there are two sets, one is a key, the other is a value, and the key is used to sort the values, this is also possible, suchSort <TKey, TValue>;
  • You can specify different comparison methods for different situations. For exampleICompare.

If the set is just a string array, it is easy to do, as shown in the following code, in ascending order:

string[] names = { "Emerson Fittipaldi", "Niki Lauda", "Ayrton Senna", "Michael Schumacher" };
Array.Sort(names);

But how do foreigners sort by their surnames based on our rules? The string array does not work, so you need to customizePersonClass, assuming the followingPersonArray:

Person[] persons = {
    new Person("Emerson", "Fittipaldi"),
    new Person("Niki", "Lauda"),
    new Person("Ayrton", "Senna"),
    new Person("Michael", "Schumacher")
};

Sort by surname in ascending order, usingSort (Array)The code below shows this method:

Array.Sort(persons);

Because of the definitionPersonClass, inheritedIComparerInterface, and implementsCompareToMethod, which specifiesLastNameThereforeArray. SortMethod.

If you wantFirstNameSort, sometimes usingLastNameWhat should I do? This requires a custom class.PersonComparer. UseSort (Array, IComparer)The code for this method is as follows:

Array.Sort(persons, new PersonComparer(PersonComparer.PersonCompareType.FirstName));
 
Console.WriteLine("Sort By First Name:");
foreach (Person p in persons)
{
    Console.WriteLine("     " + p);
}
 
Array.Sort(persons, new PersonComparer(PersonComparer.PersonCompareType.LastName));
 
Console.WriteLine("Sort By Last Name:");
foreach (Person p in persons)
{
    Console.WriteLine("     " + p);
}

Result:

Sort By First Name:
     Ayrton Senna
     Emerson Fittipaldi
     Michael Schumacher
     Niki Lauda
Sort By Last Name:
     Emerson Fittipaldi
     Niki Lauda
     Michael Schumacher
     Ayrton Senna

If we do not definePersonComparerClass, no problem, you can useSort <T> (T [], Comparison <T>)This method, parameterComparison <T>It is a generic delegate, which means we can use anonymous methods or Lambda expressions to specifyPersonThe code for comparison is as follows:

Array.Sort(persons,
    delegate(Person p1, Person p2)
    {
        return p1.FirstName.CompareTo(p2.FirstName);
    });
 
Array.Sort(persons,
    delegate(Person p1, Person p2)
    {
        return p1.LastName.CompareTo(p2.LastName);
    });

Or

Array.Sort(persons, (p1, p2) => p1.FirstName.CompareTo(p2.FirstName));
 
Array.Sort(persons, (p1, p2) => p1.LastName.CompareTo(p2.LastName));

What if we use two sets? Use one set as the key, and the other set as the value, sort by the key, as shown in the following code:

Person[] personKeys = {
    new Person("Emerson", "Fittipaldi"),
    new Person("Niki", "Lauda"),
    new Person("Ayrton", "Senna"),
    new Person("Michael", "Schumacher")
};
Person[] personValues = {
    new Person("Emerson", "Fittipaldi"),
    new Person("Niki", "Lauda"),
    new Person("Ayrton", "Senna"),
    new Person("Michael", "Schumacher")
};
 
Array.Sort<Person, Person>(personKeys, personValues);
Array.Sort<Person, Person>(personKeys, personValues, new PersonComparer(PersonComparer.PersonCompareType.FirstName));

For the generic methods of the two parameters of Sort, personValues is sorted by the LastName of the personKeys, and the generic methods of the three parameters of Sort specify that personKeys are sorted by FirstName.

 

Know the usage of Array. Sort, other methods, such as retrieval methods,BinarySearch,Find ***And indexOf.

 

References
  • . NET Framework System. Array

 

Download Demo

Related Article

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.