Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I am working on a WPF, C# application.

I am wondering how I can sort an ArrayList, i.e. a text file. I have a text file called topScore.txt and have created a file reader for the topScore.txt. However I am not sure of how I would sort this ArrayList.

This is the code for the FileReader, storing the information into scoreList, which is an arrayList.
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;

namespace TowerOfHanoi
{
    class FileReader
    {
        //Reading topScore
        static string filename1 = "topScore.txt";
        public static ArrayList readScore()
        {
            ArrayList scoreList = new ArrayList();
            //Process input file
            StreamReader sr = new StreamReader(filename1);
            String line = sr.ReadLine();
            String[] splits;
            while (line != null)
            {
                Score score = new Score();
                //Splits out parts and creates score objects
                splits = line.Split(';');
                score.name = splits[0];
                score.points = Convert.ToDouble(splits[1]);
                scoreList.Add(score);
                line = sr.ReadLine();
            }
            sr.Close();
            return scoreList;
        }

The topScore.txt contains a two dimensional information. i.e.
Mark; 1000
John; 235
Peter; 663
Sam; 345

How can I order this in terms of score. Thus so it becomes:
Mark; 1000
Peter; 663
Sam; 345
John; 235

This is just an example of how the file is structued, the file.txt is too big to order by hand. Plus new information is scores and names are entered at different stages.

There is also a class called Score, however it has an open constructor. It looks like this:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TowerOfHanoi
{
    class Score
    {
        //encapsulated data
        public string name;
        public double points;

        //Constructor
        public Score()
        {

        }
    }
}
Posted
Updated 15-Mar-11 17:34pm
v4
Comments
Toli Cuturicu 16-Mar-11 16:00pm    
Forget about ArrayList. Never use it again.

Don't use ArrayList. This type is obsolete since generics were introduced in v.2.0. Why do you need all those problems with type casting?

Instead, use the generic class System.Collections.Generic.List<T>, http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^]. For sorting use some of the Sort methods. The sorting can be done using default comparison rules (default comparer), or you can define custom comparison using custom-defined delegate of the type System.Comparison<T> or by defining a class implementing the interface System.Collections.Generic.IComparer<T>. The range sorting is also available.

Alternatively, you can use a list which is kept sorted by a key, System.Collections.Generic.SortedList<TKey, TValue>, it can be constructed using default comparer or a custom one in the form of System.Collections.Generic.IComparer<T>.

For a two-dimensional jagged array with the element type T use the list type List<List<T>>. For sorting of such thing you will certainly need a custom comparer, which is quite easy to implement.

I don't know how comparison will help you to solve the Hanoi Tower problem — there are very simple iterative and recursive algorithms, both of them, see http://en.wikipedia.org/wiki/Tower_of_Hanoi[^].

—SA
 
Share this answer
 
v5
Comments
Tarun.K.S 16-Mar-11 2:15am    
Exactly, there are so many efficient collections to work on that can provide sorting. My 5!
Sergey Alexandrovich Kryukov 16-Mar-11 2:31am    
Thank you. I would say, the problem is simpler than that, if you look at the known algorithms...
--SA
Olivier Levrey 16-Mar-11 5:05am    
Yes good answer. Have a 5.
Sergey Alexandrovich Kryukov 16-Mar-11 5:24am    
Thank you, Olivier.
--SA
Albin Abel 16-Mar-11 9:26am    
Good advice. Array List is not type safe and no way to compare different objects to give a sorting. My 5
Using IComparer<T>, as SAKryukov mentioned, is a good idea, and in your case it should look something like this:
C#
using System;
using System.Collections.Generic;

namespace Harlinn.CP.ScoreTest
{
    public class Score
    {
        private string name;
        private double value;

        public Score()
        { }
        public Score(string name, double value)
        { this.name = name; this.value = value; }

        public string Name
        {
            get { return name; }
            set { if (name == value) { return; } name = value; }
        }
        public double Value
        {
            get { return value; }
            set { if (this.value == value) { return; } this.value = value; }
        }
        public override string ToString()
        {
            string result = string.Format("{0} - {1}", Name, Value);
            return result;
        }
    }

    public class ScoreByNameComparer : IComparer<Score>
    {
        public int Compare(Score x, Score y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

    public class ScoreByDescendingValueComparer : IComparer<Score>
    {
        public int Compare(Score x, Score y)
        {
            return y.Value.CompareTo(x.Value);
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            List<Score> scores = new List<Score>();
            scores.AddRange(new Score[]
            { new Score("Humpty", 100.0),
                new Score("Dumpty", 54.0),
                new Score("Mary", 45.0),
                new Score("John", 1.0) });

            scores.Sort(new ScoreByDescendingValueComparer());
            Console.Out.WriteLine("By descending value:");
            foreach (Score score in scores) 
                { Console.Out.WriteLine(score.ToString()); }
            Console.Out.WriteLine();
            scores.Sort(new ScoreByNameComparer());
            Console.Out.WriteLine("By Name:");
            foreach (Score score in scores) 
                { Console.Out.WriteLine(score.ToString()); }

        }
    }
}


The program outputs the following:
By descending value:
Humpty - 100
Dumpty - 54
Mary - 45
John - 1

By Name:
Dumpty - 54
Humpty - 100
John - 1
Mary - 45

Regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 16-Mar-11 18:15pm    
Teamwork! However, this time you decided to take all the work in your hands, so it should by 10*5 (scratch) 16*5. Remarkable effort!
--SA
Espen Harlinn 16-Mar-11 18:38pm    
If you've ever worked with people who for some reason can't figure this out, you'll understand why. I once hired out to a "development" company with a CTO that couldn't find his a** with a map and compass - and that on a good day - much less understand why sorting is sometimes a handy thing.

Apart from giving the acronym SaaS a new meaning - Software as a Soup; when the software happended to work, it was an exercise in thumb twiddling.

So while remembering him in a seriously unfond way - I'd rather hope aswers like this can help to rid the world of similar drivel ...
Sergey Alexandrovich Kryukov 16-Mar-11 19:17pm    
Interesting. (I must say, I'm missing what's "figure _this_ out" and "understand _why_". What are _this_ and _why_ here?). I really impressed with you patience in writing and showing this code; I would see the task is pretty boring, but in real life working a way through all kind of staff no matter what it very valuable. No work is dirty if you do it well.

By the way, it has nothing to do with the Tower of Hanoi itself, right? I cannot understand, is it a game based on Tower of Hanoi or what. How can a game based on such a boring matter as Tower of Hanoi be interested in any way? Or am I missing something?

--SA
Don't use an ArrayList - use a generic collection. Once you've converted your code, check out this tip/trick:

A Generic Comparison Class for Collection Items[^]
 
Share this answer
 

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