List排序

来源:互联网 发布:淘宝上的杂货铺哪家好 编辑:程序博客网 时间:2024/06/05 08:25

1.排序的目的,往List对象中添加了一系列的字符串,想取字符串的第三位,并按如下顺序排序(1,0,2),即字符串的第三位为1的排前面,为0的排第二,为2的排最后

 

方法:

1.先添加一个自定义排序函数

        private static int MySort(string A, string B)
        {
            string chrA = "";
            string chrB = "";
            chrA = A.Substring(2, 1).ToUpper();           //取A变量的第三位放在chrA中
            chrB = B.Substring(2, 1).ToUpper();          //取B变量的第三位放在chrB中
            string SortString = "1,0,2";                            //排序规则字符串
            int IndexA = SortString.IndexOf(chrA);        //取A变量的第三位在排序规则字符串中的索引位置
            int IndexB = SortString.IndexOf(chrB);       //取B变量的第三位在排序规则字符串中的索引位置

            if (IndexA == IndexB)
            {
                return 0;
            }
            else if (IndexA < IndexB)
            {
                return -1;  //返回-1,则A会排在B的前面
            }
            else
            {
                return 1;   //返回1,则A会排在B的后面
            }
        }

2.测试

        private void btnTestListSort_Click(object sender, EventArgs e)
        {
            List<string> lstDatas = new List<string>();
            lstDatas.Add("001");
            lstDatas.Add("100");
            lstDatas.Add("101");
            lstDatas.Add("102");
            lstDatas.Add("300");
            lstDatas.Add("902");
            lstDatas.Add("200");
            lstDatas.Add("201");
            lstDatas.Sort(MySort);       //调用自定义排序方法

            //下面是输出结果显示一下

            string OutPut = "";
            for (int i = 0; i < lstDatas.Count; i++)
            {
                if (OutPut == "")
                {
                    OutPut = lstDatas[i].ToString();
                }
                else
                {
                    OutPut = OutPut + "\r\n" + lstDatas[i].ToString();
                }
            }

            MessageBox.Show(OutPut);
        }

原创粉丝点击