我需要能够对包含数字字符串属性的客户集合进行排序。
如何按数字顺序按代码对以下集合进行排序。同样,代码是一个字符串。
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/