在上一篇博文中以简单数据类型为例介绍了List。
本篇将以结构体数据类型介绍List。
下面以平面上的点为例,每个点有x、y坐标,现在要对点排序,先的x坐标的升序排列,如果x坐标相同,按照y坐标升序排列。
参考代码如下:
public struct node
{//点,结构体类型
public int x;
public int y;
};
public class Ascending : IComparer<node>
{//升序排列,先按照结构体的x字段升序,
//x字段相等时,再按照y字段升序
public int Compare(node x, node y)
{
if (x.x > y.x)
return 1;
else if (x.x == y.x)
{
if (x.y > y.y)
return 1;
else if (x.y == y.y)
return 0;
else
return -1;
}
else
return -1;
}
}
static void Main(string[] args)
{
List<node> L=new List<node>();
node t;
t.x = 7;t.y = 8;
L.Add(t);
t.x = 7; t.y = 6;
L.Add(t);
t.x = 1; t.y = 6;
L.Add(t);
t.x = 1; t.y = 5;
L.Add(t);
print(L);
L.Sort(new Ascending());//排序
print(L);
t.x = 7;t.y = 6;
int index;
index = L.BinarySearch(t, new Ascending());//折半查找
Console.WriteLine(index);
}
static void print(List<node> L)
{
for (int i = 0; i < L.Count; i++)
{
Console.Write("({0},{1}) ",L[i].x,L[i].y);
}
Console.Write("\n");
}
这篇文章总结得不错: