WPF,C#排序和二维ArrayList [英] WPF, C# Sorting and two-dimensional ArrayList

查看:111
本文介绍了WPF,C#排序和二维ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF,C#应用程序.

我想知道如何对ArrayList排序,即文本文件.我有一个名为topScore.txt的文本文件,并为topScore.txt创建了文件阅读器.但是我不确定如何对这个ArrayList进行排序.

这是FileReader的代码,将信息存储到scoreList(它是一个arrayList)中.

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.

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;
        }


topScore.txt包含二维信息.即
标记; 1000
约翰; 235
彼得663
山姆345

如何按分数排序.因此,它变为:
标记; 1000
彼得663
山姆345
约翰; 235

这只是文件结构的一个示例,file.txt太大而无法手动订购.加上新的信息是得分,并且在不同阶段输入名称.

还有一个名为Score的类,但是它具有开放的构造函数.看起来像这样:


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:

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

        }
    }
}

推荐答案

不要使用ArrayList.自从v.2.0引入泛型以来,这种类型已经过时了.为什么类型转换需要所有这些问题?

而是使用通用类System.Collections.Generic.List<T> http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx [ ^ ].要进行排序,请使用某些Sort方法.可以使用默认比较规则(默认比较器)完成排序,也可以使用类型为System.Comparison<T>的自定义委托或通过定义实现接口System.Collections.Generic.IComparer<T>的类来定义自定义比较.也可以进行范围排序.

或者,您可以使用按键System.Collections.Generic.SortedList<TKey, TValue>进行排序的列表,可以使用默认比较器或以System.Collections.Generic.IComparer<T>形式的自定义列表进行构造.

对于元素类型为T的二维锯齿状数组,请使用列表类型为List<List<T>>.要对此类内容进行排序,您肯定需要一个自定义比较器,该比较器易于实现.

我不知道比较将如何帮助您解决河内塔楼问题-都有非常简单的迭代和递归算法,两者均请参见 ^ ].

如SAKryukov所述,
—SA
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


使用IComparer< T>是个好主意,在您的情况下,它应如下所示:
Using IComparer<T>, as SAKryukov mentioned, is a good idea, and in your case it should look something like this:
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()); }

        }
    }
}



程序输出以下内容:
递减值:
矮胖-100
矮胖-54
玛丽-45
约翰-1

按名称:
矮胖-54
矮胖-100
约翰-1
玛丽-45

问候
Espen Harlinn



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


不要使用ArrayList-请使用通用集合.转换代码后,请查看以下提示/技巧:

收集项目的通用比较类 [ ^ ]
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[^]


这篇关于WPF,C#排序和二维ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆