Sort ArrayList custom objects by String element

I have a problem with sorting arraylist custom objects using string field .
This is the code I'm trying to do:

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

But I get this error:

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

What am I missing?

+3
source share
4 answers

Perhaps you should use the extension methods provided in the System.Linq namespace:

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);

If you have control over the original ArrayList and you can change its type to a typed list like this List<Portal.Entidad.Region>, I would suggest you do this. Then you will not need to throw everything afterwards and may look like this:

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

, 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());

P.S. .NET 1.1, ArrayList. .

+5

, 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<T> ( LINQ) . inline:

var results = arrRegion.OrderBy(i => i.RegNombre);
+3

System.Linq;.

arrRegion.OrderBy(x=>x.RegNombre);
+2

Source: https://habr.com/ru/post/1731444/


All Articles