c# - 对数字字符串的集合进行排序

标签 c# .net sorting

我需要能够对包含数字字符串属性的客户集合进行排序。

如何按数字顺序按代码对以下集合进行排序。同样,代码是一个字符串。

           class Program
           {
              static void Main(string[] args)
              {
                 SortableObservableCollection<Customer> customerList = new SortableObservableCollection<Customer>();
                 customerList.Add(new Customer() {Name = "Jo", Code = "1"});
                 customerList.Add(new Customer() { Name = "Jo", Code = "10" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "11" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "9" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "7" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "12" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "13" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "2" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "5" });
                 customerList.Add(new Customer() { Name = "Jo", Code = "7" });

                 //Order them by Code How
              }
           }

           public class Customer
           {
              public string Name { get; set; }
              public string Code { get; set; }
           }

谢谢你的建议

最佳答案

选项 1:实现 IComparer<Customer>并解析其中的代码

选项 2:使用 LINQ 做同样的事情:

customerList = customerList.OrderBy(c => int.Parse(c.Code)).ToList();

选项 3:更改 Customer 类,以便将数值存储为数字类型:)

编辑:如前所述,如果您向客户提供非数字代码,这将引发异常。

此外,我正在调用 ToList()因为我假设你仍然需要它作为一个列表。如果您只需要按顺序迭代结果,请使用:

IEnumerable<Customer> ordered = customerList.OrderBy(c => int.Parse(c.Code));

请注意,如果您对其进行两次迭代,它也会执行两次所有的解析和排序。

关于c# - 对数字字符串的集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719233/

相关文章:

c# - 在程序运行期间获取有关 RAM 的信息

c# - PageListPaper Html 帮助程序抛出错误 "security critical type ' System.Web.Mvc.MvcHtmlString' 失败”

.net - 在 TFS 2010 中是否有任何等效于报告者(或更改 "Created By"字段的方法)

ios - 无法排序我的NSMutablearray

javascript - 实现这个序列的最快方法是什么?

node.js - NodeJS + Node-MongoDB 原生 : sort objects in alphabet order

c# - .NET Core 3.1 Worker Service - 环境特定配置

c# - c# .net 中的物理和数学常量和基本转换库

C# 创建自定义对话框结果表单

c# - 为什么在传递对象(而不是结构)时使用 "ref"?