Clasificación Colección de objetos

Tengo esta clase:

public class Myclass
{
    public int id;
    public string name;
}

And Collection:

Collection<Myclass> myCollection = new Collection<Myclass>();

How i can sort this collection by id in place????

preguntado el 29 de julio de 12 a las 19:07

Do you actually need to use Collection<T> ? Can you switch to List<T> en lugar de ? -

how they differ? List<T> are better? -

Porque Collection<T> no tiene el Sort() método, mientras List<T> lo hace... -

6 Respuestas

Make your class implment IComparable, and define

int CompareTo(MyClass other)
{
    return Id.compareTo(other.Id);
}

Then any standard sort functions can be used.

Respondido 29 Jul 12, 19:07

Linq is the most straightforward way

var sorted = (from my in myCollection orderby my.id select my).ToList();

Respondido 29 Jul 12, 19:07

Do like this with lambda expreesion:

myCollection.Sort((a,b) => a.id.CompareTo(b.id));

Si su clase implementa IComparable<T> de la siguiente manera:

public class Myclass : IComparable<Myclass> {
   public int id;
   public string name; 

    public int CompareTo(Myclass myClass) {
        return id.CompareTo(myClass.id);
    }
}

Then, you directly can call Sort() método:

   myCollection.Sort();

I have used myCollection as for you but indeed it do not have Sort() method....Instead, you can make your myCollection to List so that list can use Sort() método.

Respondido 30 Jul 12, 04:07

@AlexF: Actually this answer is not completely accurate. If you use the first line you don't need to change MyClass (i.e. no need to implement IComparable<>). Instead, if MyClass implementos IComparable<> like in the last code snippet, you can use directly myCollection.Sort() without any lambda expression. Finally, Collection<> no tiene metodo Sort(); List<> lo hace. - DigEmAll

@digEmAll: you are right! I decided to use List<T> in my project, thanks to you! I do not know why, but I thought that the collection is better than a list, but it turned out the opposite - alex f

Collection<Myclass> ss = new Collection<Myclass>();
var ordered=ss.OrderBy(s => s.id).ToList();

now order will be a list of MyClass object order by the ID

Respondido 29 Jul 12, 19:07

I suggest you to use List instead of Collection. For sorting you can use Linq operator OrderBy.

List<Myclass> items = new List<Myclass>();
// Add items here
items=items.OrderBy(item=>item.Id).ToList();

Respondido 29 Jul 12, 19:07

Collection myCl= new Collection();

var res = myCl.OrderBy(mc=>mc.Id).ToList();

Respondido 29 Jul 12, 19:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.