I have this class:
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????
Do like this with lambda expreesion:
myCollection.Sort((a,b) => a.id.CompareTo(b.id));
If your class implements IComparable<T> in following way:
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() method:
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() method.
MyClass (i.e. no need to implement IComparable<>). Instead, if MyClass implements IComparable<> like in the last code snippet, you can use directly myCollection.Sort() without any lambda expression. Finally, Collection<> has no method Sort(); List<> does.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
Collection<T>? Can you switch toList<T>instead ?Collection<T>doesn't have theSort()method, whileList<T>does...