如何使用带有c#的struct和arraylist按字母顺序排序

本文关键字:arraylist 排序 顺序 struct 何使用 | 更新日期: 2023-09-27 18:00:39

THX所有人。使用LIST<>相反,ARRAYLIST对很有帮助

所以我举了一个结构,它包含了关于工人的信息,工人的名字,他的工作,他在这份工作上做了多少工作,以及他赚了多少钱,这些信息我用字符串保存在文件中,解释:尼克,道路工人,5200。我有8个类似expl的thoose字符串,我需要使用arraylist和struct,根据worker的名称对它们进行排序,plz help!

//Struct
 public struct Worker
{
    public string FIO;
    public string Dolj;
    public int Staj;
    public int Zp;
    public Worker(string fi, string dj, int st, int zrp)
    {
        FIO = fi;
        Dolj = dj;
        Staj = st;
        Zp = zrp;
    }
//reading from file
ArrayList listw = new ArrayList();
            Worker W;
            StreamReader file= new StreamReader("Workers.txt", Encoding.Default);
          ;
            while (!file.EndOfStream)
            {
                string[] wtemp = file.ReadLine().Split(',');
                W = new Worker(wtemp[0],wtemp[1],Convert.ToInt32(wtemp[2]),Convert.ToInt32(wtemp[3]));
                listw.Add(W);
            }
//display listw
//!!!!! So here i need to sort arraylist or struct by FIO (name of worker)
// Arraylist - listw 
// (Name,job,years,money)
// (Name,job,years,money) --Sort by name!
 foreach (Worker outworker in listw)
            {
                Console.WriteLine
                (outworker.FIO,outworker.Dolj,outworker.Staj,outworker.Zp);
            }

如何使用带有c#的struct和arraylist按字母顺序排序

您可以使用LINQ:

var orderedWorkers = listw.OfType<Worker>().OrderBy(x => x.FIO).ToList();

为了类型安全,请始终使用List<T>类而不是ArrayList

另一种选择是为您的类型实现自定义Comparer

public struct NameComparer : IComparer
{
    public int Compare(object x, object y)
    {
        if (x is Worker && y is Worker)
        {
            return ((Worker)x).FIO.CompareTo(((Worker)y).FIO);
        }
        return 0;
    }
}

然后只需调用Sort方法:

 listw.Sort(new NameComparer());

//从文件读取

List<Worker> listw = new List<Worker>();
Worker W;
StreamReader file= new StreamReader("Workers.txt", Encoding.Default);
while (!file.EndOfStream)
{
    string[] wtemp = file.ReadLine().Split(',');
    W = new Worker(wtemp[0],wtemp[1],Convert.ToInt32(wtemp[2]),Convert.ToInt32(wtemp[3]));
    listw.Add(W);
}
//Sort by name.
listw = listw.OrderBy(x=> x.FIO).ToList();
foreach (Worker outworker in listw)
{
    Console.WriteLine(outworker.FIO,outworker.Dolj,outworker.Staj,outworker.Zp);
}

将listw类型更改为List<Worker>,就可以轻松地进行LINQ排序。

foreach (var outworker in listw.OrderBy(worker => worker.FIO))
{
    Console.WriteLine(outworker.FIO, outworker.Dolj, outworker.Staj, outworker.Zp);
}