c# - 基于整数顺序的字符串列表排序

标签 c# .net asp.net

我有列表。尽管数据类型为字符串,但此列表仅包含整数值。我想根据项目的整数顺序对列表进行排序。

如何实现?

List<string> newZipCodesList = new List<string>();

最佳答案

您可以使用 IComparer 接口(interface)来实现您自己的排序。您将必须创建一个类,该类将实现 T 的 IComparer,其中 T 在本例中为字符串。

   newZipCodesList.Sort(new Test());

   public class Test : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            //return 1 when first is greater than second
            if(Convert.ToInt32(x) > Convert.ToInt32(y))
                return 1;
            //return -1 when first is less than second
            else if (Convert.ToInt32(x) < Convert.ToInt32(y))
                return -1;
            //return 0 if they are equal
            else
                return 0;
        }
    }

关于c# - 基于整数顺序的字符串列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889992/

相关文章:

c# - 编译器是否优化对 const 变量和文字 const 数字的操作?

c# - 如何禁用 Newtonsoft JSON 序列化程序中的对象引用创建?

c# - 用户在 asp.net MVC 3 url 中输入正斜杠 "/"

c# - ASP.NET MVC 中 TextBoxFor 的默认值

c# - 作为参数传递从 C# 中的类派生的对象

c# - Entity Framework 4.1 Linq Contains 和 StartsWith

c# - 如何获取 Windows 中所有打开的命名管道的列表并避免可能的异常?

c# - 使用泛型属性调用重载方法会调用错误的重载

c# - 从客户端下载 Silverlight 文件

javascript - javascript 和 c# 在将数组传递给函数并在函数内部替换它时的区别