刚使用sort排序又又又又又忘了,返回1(大于0即可),-1(小于0即可)是怎么排序了,果然是年纪大了。
sort返回
void Start()
{
List<int> tempList = new List<int>() {2,3,9,3,4 };
tempList.Sort((a,b)=> {
if (a>b)
return 1;
if (a==b)
return 0;
if (a < b)
return -1;
return 0;
});
string result = " ";
foreach (var item in tempList)
{
result += item + " ";
}
Debug.LogError(result);
//---输出 2 3 3 4 9
//-从小到大排序。反之如果想要从大到小排序则:a>b return -1;a<b return 1;
}
排序的几种实现方式
List.Sort(Comparison comparison)
上面的示例其实就是这种方式,只不过使用的匿名表达式,如果显示的使用可以像这样
int TestComparison(int a,int b)
{
if (a > b)
return 1;
if (a == b)
return 0;
if (a < b)
return -1;
return 0;
}
void Start()
{
List<int> tempList = new List<int>() {2,3,9,3,4 };
Comparison<int> comparison = TestComparison;
tempList.Sort(comparison);
string result = " ";
foreach (var item in tempList)
{
result += item + " ";
}
Debug.LogError(result);
---输出 2 3 3 4 9
}
List.Sort(IComparer Comparer)
存储的元素实现IComparable接口,可以直接进行排序
public class CustomSort : IComparable<CustomSort>
{
public CustomSort(int num)
{
this.num = num;
}
public int num;
public int CompareTo(CustomSort other)
{
if (num > other.num)
return 1;
if (num == other.num)
return 0;
if (num <other.num)
return -1;
return 0;
}
}
void Start()
{
List<CustomSort> tempList = new List<CustomSort>() {new CustomSort(2),
new CustomSort(3),new CustomSort(9),new CustomSort(3),new CustomSort(4)};
tempList.Sort();
string result = " ";
foreach (var item in tempList)
{
result += item.num + " ";
}
Debug.LogError(result);
}
以上就是排序的用法,希望以后不会看这个了,记性太差了