c# - 按 String 成员对自定义对象的 ArrayList 进行排序

标签 c# sorting arraylist

我在按字符串 字段对自定义对象的arraylist 进行排序时遇到问题。
这是我正在尝试执行的代码:

arrRegion.Sort(delegate(Portal.Entidad.Region x, Portal.Entidad.Region y)
                           {
                               return x.RegNombre.CompareTo(y.RegNombre);
                           });

但是我收到了这个错误:

Argument type 'anonymous method' is not assignable to parameter type 'System.Collection.IComparer'

我错过了什么?

最佳答案

也许您应该使用 System.Linq 命名空间中提供的扩展方法:

using System.Linq;
//...

// if you might have objects of other types, OfType<> will
// - filter elements that are not of the given type
// - return an enumeration of the elements already cast to the right type
arrRegion.OfType<Portal.Entidad.Region>().OrderBy(r => r.RegNombre);

// if there is only a single type in your ArrayList, use Cast<>
// to return an enumeration of the elements already cast to the right type
arrRegion.Cast<Portal.Entidad.Region>().OrderBy(r => r.RegNombre);

如果您可以控制原始 ArrayList,并且可以将其类型更改为类型化列表,如下所示 List<Portal.Entidad.Region> ,我建议你这样做。然后你就不需要在之后转换所有东西并且可以像这样排序:

var orderedRegions = arrRegion.OrderBy(r => r.RegNombre);

关于c# - 按 String 成员对自定义对象的 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202185/

相关文章:

java - 对 java ConcurrentHashMap 中的值进行排序

java - Android:如何将 ArrayList 的每个值绑定(bind)到一个变量?

java - 如何在java中使用printf()打印表格?

c# - 无法获取 nuget 包 zlib.portable

javascript - 将数字数组缩减为固定长度的较小数字数组

java - 快速排序不对长度为 2 的数组进行排序

java - 合并两个没有重复子类的ArrayList

c# - 使用 .NET 响应式(Reactive)扩展而不是以下 'Run if not Running' 模式

c# - 将 WSDL 导入 .NET 项目只会创建一个空的命名空间

c# - NewtonSoft.Json 自定义 JsonConverter 反序列化到 DateTime 不工作