在比较方法中需要实现对象比较规则,这个方法实现后,就可以把这方名字作为参数委托给List的Sort方法,Sort方法在排序时会执行这个方法对List中的对象进行比较

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace listSort
{
public class StrItem
{
public int id;
public int num;
}
class Program
{
static void Main(string[] args)
{
delegateSort();
Console.ReadLine();
}

static int sort(StrItem str1,StrItem str2)
{
int ret = 0;
if (str1.id > str2.id) //id从小到大
{
return 1;
}
else if (str1.id == str2.id)
{
if (str1.num < str2.num)//num从大到小
{
return 1;
}
}
return ret;
}

static void delegateSort()
{
List<StrItem> listItem = new List<StrItem>();
StrItem str1 = new StrItem();
str1.id = 1;
str1.num = 0;
listItem.Add(str1);

StrItem str2 = new StrItem();
str2.id = 2;
str2.num = 3;
listItem.Add(str2);

StrItem str3 = new StrItem();
str3.id = 2;
str3.num = 4;
listItem.Add(str3);

listItem.Sort(sort);
foreach (var item in listItem)
{
Console.WriteLine(item.num);
}
}
}
}

输出结果:

c# list 委托排序_c#