0

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????

3
  • Do you actually need to use Collection<T> ? Can you switch to List<T> instead ? Commented Jul 29, 2012 at 18:20
  • how they differ? List<T> are better? Commented Jul 29, 2012 at 18:24
  • Because Collection<T> doesn't have the Sort() method, while List<T> does... Commented Jul 29, 2012 at 19:35

6 Answers 6

6

Make your class implment IComparable, and define

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

Then any standard sort functions can be used.

Sign up to request clarification or add additional context in comments.

Comments

3

Linq is the most straightforward way

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

Comments

2

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.

2 Comments

@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 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.
@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
0
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

Comments

0

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

Comments

0

Collection myCl= new Collection();

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.