按String成员对自定义对象的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().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().OrderBy(r => r.RegNombre);
如果您可以控制原始ArrayList,并且可以将其类型更改为类似List
的类型列表,我建议您这样做。 然后你不需要在之后投射所有内容并且可以像这样排序:
var orderedRegions = arrRegion.OrderBy(r => r.RegNombre);
这是因为Sort方法需要一个不能作为委托的IComparer实现。 例如:
public class RegionComparer : IComparer { public int Compare(object x, object y) { // TODO: Error handling, etc... return ((Region)x).RegNombre.CompareTo(((Region)y).RegNombre); } }
然后:
arrRegion.Sort(new RegionComparer());
PS除非你仍然坚持使用.NET 1.1,否则不要使用ArrayList 。 而是使用一些强类型集合。
您需要实际创建一个实现IComparer的类,并提供它。
这可以通过私人课程来完成:
private class RegNombreComparer: IComparer { int IComparer.Compare( Object xt, Object yt ) { Portal.Entidad.Region x = (Portal.Entidad.Region) xt; Portal.Entidad.Region y = (Portal.Entidad.Region) yt; return x.RegNombre.CompareTo(y.RegNombre); } }
然后,你做:
arrRegion.Sort(new RegNombreComparer());
这是ArrayList的一个缺点,为什么使用List
(特别是LINQ)可能是有利的。 它简化了这一点,并允许您指定内联排序:
var results = arrRegion.OrderBy(i => i.RegNombre);
您也可以使用System.Linq;
。
arrRegion.OrderBy(x=>x.RegNombre);