. NET Framework System. Array. Sort Array class, deepen understanding of IComparer, IComparable, generic delegate, anonymous method, Lambda expression, Generic Array
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.
Custom
PersonClass
PersonThe class 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 defaultLastNameSort in ascending order.
Custom
PersonComparerClass
This class internally defines a comparison type, you can pressFirstNameOrLastNameAnd are sorted in ascending order.PersonComparerClass inheritanceIComparerThe non-generic and generic interfaces implement their correspondingCompareMethod.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 sorted by default, which is generally ascending or descending;
- 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 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 scenarios. For exampleICompare. You can specify ascending or descending LastName or FirstName.
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 their surnames according to our habits? The string array certainly does not work, which requires customPersonClass, assuming there are the followingPersonArray:
Person[] persons = {
new Person("Emerson", "Fittipaldi"),
new Person("Niki", "Lauda"),
new Person("Ayrton", "Senna"),
new Person("Michael", "Schumacher")
};
UseSort (Array)This method is sorted in ascending order of the last name, as shown in the following code:
Array.Sort(persons);
Because of the definitionPersonClass, inheritedIComparerInterface, and implementsCompareToMethod, which specifiesLastNameComparison, and in ascending order, soArray. 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>Is a generic delegate provided by. Net, which means that we can use anonymous methods or Lambda expressions to specifyPersonThe following table describes how to compare data using the anonymous method:
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 use Lambda expressions:
Array.Sort(persons, (p1, p2) => p1.FirstName.CompareTo(p2.FirstName));
Array.Sort(persons, (p1, p2) => p1.LastName.CompareTo(p2.LastName));
If there are two sets, how can one set be sorted by another set? If there are twoPersonThe set is exactly the same. It is only one key and the other value, which is sorted 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));
Where,
- SortThere are two parameter generic methods,PersonValuesPressPersonKeysOfLastNameSort in ascending order. This is the default value;
- SortThere are three parameter generic methods,PersonValuesPressPersonKeysOfFirstNameSort in ascending order.
ArrayOther methods in, suchBinarySearch,FindRelated andIndexOfRelatedSortSimilar in usage, because most of their parameters areIComparer, IComparableAnd generic delegation.
References
- . NET Framework System. Array
Download Demo