[英]Generic Sort for Number or Alphabet in Ascending or Descending Order
How can I sort Generic array which can contain alphabet or numbers only? 如何排序仅包含字母或数字的通用数组?
Lets say I have a generic list of array that contains numbers only and can be easily sort using
可以说我有一个数组的通用列表,该列表仅包含数字,可以使用以下命令轻松进行排序
public void sortAsc(ref T[] obj)
{
do
{
didSwap = false;
for (int i = 0; i < obj.Length - 1; i++)
{
if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))
{
T temp = obj[i + 1];
obj[i + 1] = obj[i];
obj[i] = temp;
didSwap = true;
}
}
} while (didSwap);
}
but if array contains string of names and we wants to sort in same way will fail. 但是如果数组包含名称字符串并且我们想要以相同的方式排序将失败。
due to this 由于这个
if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))
如果(Convert.ToInt32(obj [i])<Convert.ToInt32(obj [i + 1]))
Please let me know if there is a generic method for this or I will have to separate logic for each. 请让我知道是否有一个通用的方法,否则我将不得不为每个逻辑分开。
Take a look at the List<T>.Sort()
method as this will do what you need. 看一下
List<T>.Sort()
方法,因为这将满足您的需求。
It solves your problem of having to use Convert.ToInt32
because by default it will use the IComparer
implementation of the actual class being used, which both int
and string
have already for you. 它解决了您必须使用
Convert.ToInt32
问题,因为默认情况下,它将使用所使用的实际类的IComparer
实现, int
和string
都已为您提供。
So for strings: 所以对于字符串:
var list = new List<string> { "dd", "aa", "ss" };
list.Sort();
//Output: list = ["aa", "dd", "ss"]
Or for integers: 或对于整数:
var list = new List<int> { 1, 13, 5 };
list.Sort();
//Output: list = [1, 5, 13]
If you want to work with custom classes, just make your class implement IComparable
or by having the caller to Sort()
to provide a function delegate to use. 如果要使用自定义类,只需使您的类实现
IComparable
或通过让Sort()
的调用者提供要使用的函数委托即可。 See the first link for more details in the docs. 有关文档的更多详细信息,请参见第一个链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.