Search code examples
c#arraylist.net-2.0

Arraylist sorting in c#


I am trying to modify this code that already exists.The code was developed around 2008 and I am trying to fix the sort issue. I am also thinking of changing the code but wanted to fix the issue first.

ArrayList lineEmpNrs = new ArrayList();
taMibMsftEmpDetails employeeDetails; //taMibMsftEmpDetails is a custom class file

while (!HeaderFile.EndOfStream) //headerfile is employee information text file.
{
    headerRow = HeaderFile.ReadLine();
    headerFields = headerRow.Split(',');
    employeeDetails = BuildLine(headerFields[1],headerFields[2],headerFields[3]);
    lineEmpNrs.Add(employeeDetails);
}

 private taMibMsftEmpDetails BuildLine(string EmpId, string EmpName, String ExpnsDate)
 {
     taMibMsftEmpDetails empSlNr = new taMibMsftEmpDetails();
     empSlNr.EmployeeId  = EmpId;
     empSlNr.EmployeeName   = EmpName;
     empSlNr.ExpenseDate = ExpnsDate;
     return empSlNr;
 }

The Headerfile contains employee expense details. The empID is the key here and the headerFile can contain 'n' number of lines with same EmpID appearing in random order in the file.

I use lineEmpNrs to build some other information based on EmpID. So I want to have lineEmpNrs sorted based on EmpID. I tried the regular sort method but it didn't work.

Please suggest.


Solution

  • This code is .Net 2.0 safe:

    public static string ReadLines(StreamReader input)
    {
        string line;
        while ( (line = input.ReadLine()) != null)
           yield return line;
    }
    
    private taMibMsftEmpDetails BuildLine(string EmpId, string EmpName, String ExpnsDate)
    {
        taMibMsftEmpDetails empSlNr = new taMibMsftEmpDetails();
        empSlNr.EmployeeId  = EmpId;
        empSlNr.EmployeeName   = EmpName;
        empSlNr.ExpenseDate = ExpnsDate;
        return empSlNr;
    }
    
    List<taMibMsftEmpDetails> lineEmpNrs = new List<taMibMsftEmpDetails>();
    foreach (string line in ReadLines(HeaderFile))
    {
        headerFields = line.Split(',');
        lineEmpNrs.Add(BuildLine(headerFields[1],headerFields[2],headerFields[3]));
    }
    lineEmpNrs.Sort(delegate(taMibMsftEmpDetails a, taMibMsftEmpDetails a) 
       { 
          return a.EmployeeId.CompareTo(a.EmployeeId); 
       });    
    

    If you can get to at least .Net 3.5 (still uses .Net 2.0 runtime), it gets that much simpler:

    public static string ReadLines(StreamReader input)
    {
        string line;
        while ( (line = input.ReadLine()) != null)
           yield return line;
    }
    
    var lineEmpNrs = ReadLines(HeaderFile)
       .Select(l => l.Split(','))
       .Select(l => new taMibMsftEmpDetails() 
           {
              EmployeeId   = l[1],
              EmployeeName = l[2],
              ExpenseDate  = l[3]
           })
       .OrderBy(l=> l.EmployeeId)
       .ToList();