lid*_*min 3 c# sorting arraylist
我有一个问题是通过字符串字段排序自定义对象的arraylist.
这是我要做的代码:
arrRegion.Sort(delegate(Portal.Entidad.Region x, Portal.Entidad.Region y)
{
return x.RegNombre.CompareTo(y.RegNombre);
});
Run Code Online (Sandbox Code Playgroud)
但是我收到了这个错误:
Argument type 'anonymous method' is not assignable to parameter type 'System.Collection.IComparer'
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
也许您应该使用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);
Run Code Online (Sandbox Code Playgroud)
如果您可以控制原始ArrayList,并且可以将其类型更改为类似的类型列表List<Portal.Entidad.Region>
,我建议您这样做.然后你不需要在之后投射所有内容并且可以像这样排序:
var orderedRegions = arrRegion.OrderBy(r => r.RegNombre);
Run Code Online (Sandbox Code Playgroud)
这是因为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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
arrRegion.Sort(new RegionComparer());
Run Code Online (Sandbox Code Playgroud)
PS除非你仍然坚持使用.NET 1.1,否则不要使用ArrayList.而是使用一些强类型集合.