THX ALL OF YOU。使用列表<> INSTEAD ARRAYLIST很有帮助
所以我提出了一个结构,其中包含有关工人的信息,工人的fio名称,dolj-他的工作,staj-他在这份工作上的工作量和zp-他花了多少钱,这些信息我保存在档案中有字符串,探索:尼克,道路工人,5,200。我有8个thoose字符串像expl,我需要按工人的名字对它们进行排序,使用arraylist和struct,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);
}
答案 0 :(得分:3)
您可以使用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());
答案 1 :(得分:0)
将您的listw类型更改为List<Worker>
,您可以轻松地进行LINQ排序。
foreach (var outworker in listw.OrderBy(worker => worker.FIO))
{
Console.WriteLine(outworker.FIO, outworker.Dolj, outworker.Staj, outworker.Zp);
}
答案 2 :(得分:0)
//从文件中读取
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);
}