我在按字符串 字段对自定义对象的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/