Ok, I have this posted in the C# 2005, but I realized that the studio I'm using is the newest, while the book is 2005 :D
This is running as a console app, not a win app.
I'm reading in a CSV file containing 5 elements per line into a list of objects, and I want to sort on the third element of the line. So, if the CSV line is this:
34919, 12, 0444, 20, Some Text
I want to sort on 0444. Currently it's not doing it.
Here's my code:
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace prgOne
{
public class csvLineComparer : IComparer
{
public static IComparer Default = new csvLineComparer();
public int Compare(object x, object y)
{
if (x is csvLine && y is csvLine)
{
return Comparer.Default.Compare(((csvLine)x).clNumb, ((csvLine)y).clNumb);
}
else
{
throw new ArgumentException("One or both objects to compare are not csvLine objects.");
}
}
}
}
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace prgOne
{
class csvLine : IComparable
{
public string clTime;
public string clChan;
public int clNumb;
public string clStat;
public string clDesc;
public csvLine(string cltime, string clchan, int clnumb, string clstat, string cldesc)
{
clTime = cltime;
clChan = clchan;
clNumb = clnumb;
clStat = clstat;
clDesc = cldesc;
}
public int CompareTo(object obj)
{
if (obj is csvLine)
{
csvLine otherLine = obj as csvLine;
return this.clNumb - otherLine.clNumb;
}
else
{
throw new ArgumentException("Object to compare is not a line.");
}
}
}
}
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace prgOne
{
class Program
{
static void Main(string[] args)
{
string[] strArray;
string strLine;
char[] charArray = new char[] { ',' };
FileStream aFile = new FileStream("C:\\csharp\\diag.log", FileMode.Open);
StreamReader sr = new StreamReader(aFile);
ArrayList lines = new ArrayList();
strLine = sr.ReadLine();
while (strLine != null)
{
strArray = strLine.Split(charArray);
lines.Add(new csvLine(strArray[0], strArray[1], Convert.ToInt16(strArray[2]), strArray[3], strArray[4]));
strLine = sr.ReadLine();
}
sr.Close();
for (int i = 0; i < lines.Count; i++)
{
Console.WriteLine("{0}, {1}, {2}, {3}, {4}", (lines[i] as csvLine).clTime, (lines[i] as csvLine).clChan, (lines[i] as csvLine).clNumb, (lines[i] as csvLine).clStat, (lines[i] as csvLine).clDesc);
}
Console.ReadKey();
}
}
}