Link to home
Start Free TrialLog in
Avatar of techbro
techbroFlag for United States of America

asked on

How to sort() a custom class?

I am studying for MCTS exam, and figuring out how to sort custom class by sort() method.
I have created a "Burger" class, implemented IComparable, accessor variable, and inserted some integers inside 6 instances of class. But I am not sure how to sort them by sort() method so that I could print the integers in asecending order by Console.WriteLine().
Can you provide me inputs how to use sort() in such circumstance?

The code is given below:

namespace CustomClassSort
{

    class Burger : IComparable<Burger>
    {
        private int burger;
        public Burger(int burger)
        {
            this.burger = burger;
        }

        public int CompareTo(Burger other)
        {
            return this.iloveburger.CompareTo(other.iloveburger);            
        }

        public int iloveburger
        {
            get
            {
                return this.burger;
            }
            set
            {
                this.burger = value;
            }
        }
       
    }
    
    class IDateABurger
    {
        static void Main(string[] args)
        {
            Burger a = new Burger(2);
            Burger b = new Burger(22);
            Burger c = new Burger(12);
            Burger d = new Burger(33);
            Burger e = new Burger(44);
            Burger f = new Burger(5);

        }
    }
} 

Open in new window


Let me know if you have any question.

P.S: I don't actually date a burger. :)
Avatar of kaufmed
kaufmed
Flag of United States of America image

Look at the overloads for Sort and see if you can tell how you might use that to sort  ; )
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
try:

public int compareTo(Burger other) {
        If (this.Burger < other.Burger) return -1;
        If (this.Burger == other.Burger) return 0;
        If (this.Burger > other.Burger) return +1;
}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or using lambda:
Burger[] arr = new Burger[]{a,b,c,d,e,f};
foreach(var item in arr.OrderBy(m=>m.iloveburger))
Console.WriteLine(item.iloveburger);
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@morgulo
That's not going to help him for the MCTS exam  ; )
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of techbro

ASKER

Thanks for input.
I will add another post in the "Related Question" option, if I have more questions.