// 要存在list中的节点信息
class Node
{
public int nID;
public int nValue;
}

// 打印list所有的节点
static void print(List<Node> nodeList)
{
for (int i = 0; i < nodeList.Count; i++)
{
Console.WriteLine(nodeList[i].nID.ToString() + " , " + nodeList[i].nValue.ToString());
}
Console.WriteLine("");
}

static void Main(string[] args)
{
// 创建一个list,里面随机压入一些节点信息
List<Node> nodeList = new List<Node>();
nodeList.Add(new Node() { nID = 1, nValue = 999 });
nodeList.Add(new Node() { nID = 2, nValue = 67 });
nodeList.Add(new Node() { nID = 5, nValue = 356 });
nodeList.Add(new Node() { nID = 4, nValue = 20 });
nodeList.Add(new Node() { nID = 3, nValue = 133 });

// 以ID进行升序
nodeList.Sort(
delegate(Node n1, Node n2)
{
return n1.nID.CompareTo(n2.nID);
}
);

Console.WriteLine("以ID进行升序后的结果:");
print(nodeList);

// 以ID进行降序
nodeList.Sort(
delegate(Node n1, Node n2)
{
return n2.nID.CompareTo(n1.nID);
}
);

Console.WriteLine("以ID进行降序后的结果:");
print(nodeList);

// 以Value进行升序
nodeList.Sort(
delegate(Node n1, Node n2)
{
return n1.nValue.CompareTo(n2.nValue);
}
);

Console.WriteLine("以Value进行升序后的结果:");
print(nodeList);

// 以Value进行降序
nodeList.Sort(
delegate(Node n1, Node n2)
{
return n2.nValue.CompareTo(n1.nValue);
}
);

Console.WriteLine("以Value进行降序后的结果:");
print(nodeList);

Console.ReadKey();
}

测试结果如下图:

c# list 自定义排序_i++