Click here to Skip to main content
15,884,425 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using c# language and doing this on console based application. The problem i am having is sorting. i need to produce two things. first is sorting alphabetically, second is sorting numerically. I add products and quantity myself so there is no fixed arraylist as such. i want to know how to sort it based on what i enter into the console. does this make sense?
C#
     public class TheoVendingMachine
  {
      private ArrayList merchandises;
      public MoneySet moneys;
      public MoneySet currentMoneys;
      public TheoVendingMachine()
      {
          this.merchandises = new ArrayList();
          this.moneys = new MoneySet();
          this.currentMoneys = new MoneySet();
      }
      public Merchandise[] getProductTypes()
      {

          ArrayList arrayList = new ArrayList();
          arrayList.Sort();
          foreach (Merchandise product in this.merchandises)
          {
              if (!arrayList.Contains(product))
              {
                  arrayList.Add(product);
              }

          }

Merchandise[] array = new Merchandise[arrayList.Count];

          for (int i = 0; i < arrayList.Count; i++)
          {
              array[i] = (Merchandise)arrayList[i];
              arrayList.Sort();
          }


          return array;
      }
Posted
Updated 3-Dec-14 6:25am
v3

1 solution

What you enter in the console is always text - so if you want to sort things numerically, you need to convert the text to a number:
C#
string s = Console.ReadLine();
int i;
if (int.TryParse(s, out i))
   {
   // Valid integer entered
   ...
   }
else
   {
   // Tell the user that isn't a number...
   ...
   }


And I wouldn't use an ArrayList - use a typed array or List<T> - that way you don;t have to cast it to the desired type before you use it.
So...Set up either a class to contain the string and integer value together then use a List<T>of that class, or set up two Lists (one of string and one of int) and sort them appropriately.

You know how to do that, yes?
 
Share this answer
 
Comments
Member 11283684 3-Dec-14 12:40pm    
No i am not familiar with doing that :/ I am new to this sorry, maybe there are some links to help me you know of?
THankyou
OriginalGriff 3-Dec-14 14:08pm    
Well, you already know how to sort a collection - you do it in your code.
And you know how to create a class - again, you do that in your code above.

So which bit is giving you problems?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900