本文实例讲述了c#数组排序的两种常用方法。分享给大家供大家参考。具体如下:
1.第一个例子
定义代码
#region array数组排序1 public class pigeon : icomparable<pigeon> //类元素本身继承比较接口 { int xvalue; int yvalue; public string batchno { get; set; } public int compareto(pigeon other) { if (other == null) throw new argumentnullexception("比较参数为空"); //按第三个字符比较 xvalue = convert.toint32(this.batchno.substring(2, 1)); yvalue = convert.toint32(other.batchno.substring(2, 1)); if (xvalue == yvalue) { return 0; } else if (xvalue < yvalue) { return -1; //返回-1,x排在y的前面 } else { return 1; //返回1,x排在y的后面 } } } #endregion
测试代码
#region 测试array数组排序1 private void button3_click(object sender, eventargs e) { pigeon[] pigeons = new pigeon[]{ new pigeon(){batchno="1256"}, new pigeon(){batchno="1236"}, new pigeon(){batchno="1276"}, new pigeon(){batchno="1216"} }; array.sort(pigeons); string resultmsg = ""; foreach (pigeon o in pigeons) { resultmsg += o.batchno + "\r\n"; } messagebox.show(resultmsg); } #endregion
1.第二个例子
定义代码
#region array数组排序 public class mybatch //数组元素类 { public string batchno { get; set; } } public enum comparetype //比较类型枚举 { threechar =0, fourchar=1 } public class mybatchcompare:icomparer<mybatch> //定义了一个比较类 { private comparetype comparetype;//定义排序类型 public mybatchcompare(comparetype comparetype) { //构造函数中初始化比较类型 this.comparetype = comparetype; } public int compare(mybatch x, mybatch y) { int xvalue; int yvalue; if (x == null) throw new argumentnullexception("x值为空"); if (y == null) throw new argumentnullexception("y值为空"); switch (comparetype) { case comparetype.threechar: //按第三个字符比较从小到大排序 xvalue = convert.toint32(x.batchno.substring(2,1)); yvalue = convert.toint32(y.batchno.substring(2,1)); if (xvalue == yvalue) { return 0; } else if (xvalue < yvalue) { return -1; //返回-1,x排在y的前面 } else { return 1; //返回1,x排在y的后面 } case comparetype.fourchar: //按第四个字符比较从小到大排序 xvalue = convert.toint32(x.batchno.substring(3,1)); yvalue = convert.toint32(y.batchno.substring(3,1)); if (xvalue == yvalue) { return 0; } else if (xvalue < yvalue) { return -1; //返回-1,x排在y的前面 } else { return 1; //返回1,x排在y的后面 } default: throw new argumentexception("比较类型参数错误"); } } } #endregion
测试代码
#region array数组排序 private void button2_click(object sender, eventargs e) { mybatch[] batchs ={ new mybatch(){batchno="1234"}, new mybatch(){batchno="1263"}, new mybatch(){batchno="1218"}, new mybatch(){batchno="1242"} }; //按第三个字符从小到大排 array.sort(batchs,new mybatchcompare(comparetype.threechar)); string resultmsg = ""; foreach (mybatch o in batchs) { resultmsg += o.batchno + "\r\n"; } messagebox.show(resultmsg); //按第四个字符从小到大排序 array.sort(batchs, new mybatchcompare(comparetype.fourchar)); resultmsg = ""; foreach (mybatch o in batchs) { resultmsg += o.batchno + "\r\n"; } messagebox.show(resultmsg); } #endregion
希望本文所述对大家的c#程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论