C# Programming
09-04-2009, 07:23 PM
Hi. I'm now using the SortedList to sort the strings from the text file. Is it possible to have a single key as the basis for comparing each string? If yes, I want to know how i will prevent the key from duplicating. Can someone help me?
As of now this is what I accomplished:
public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
{
Console.Clear();
int vehicleCountInt = 0;
Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\n");
using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
{
vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
countVehicle.Close();
}
SortedList sortedLastName = new SortedList(vehicleCountInt);
using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
{
for (int i = 0; i < vehicleCountInt; i++)
{
arrayOfLastNames[i] = outputLastNames.ReadLine();
string keyVal = arrayOfLastNames[i];
sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException
if (!sortedLastName.ContainsKey(keyVal))
{
sortedLastName.Add(keyVal, arrayOfLastNames[i]);
}
else
{
sortedLastName.Remove(keyVal);
sortedLastName.Add(keyVal, arrayOfLastNames[i]);
}
Console.WriteLine("{0}", sortedLastName.Keys[i]);
}
outputLastNames.Close();
}
}
As of now this is what I accomplished:
public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
{
Console.Clear();
int vehicleCountInt = 0;
Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\n");
using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
{
vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
countVehicle.Close();
}
SortedList sortedLastName = new SortedList(vehicleCountInt);
using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
{
for (int i = 0; i < vehicleCountInt; i++)
{
arrayOfLastNames[i] = outputLastNames.ReadLine();
string keyVal = arrayOfLastNames[i];
sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException
if (!sortedLastName.ContainsKey(keyVal))
{
sortedLastName.Add(keyVal, arrayOfLastNames[i]);
}
else
{
sortedLastName.Remove(keyVal);
sortedLastName.Add(keyVal, arrayOfLastNames[i]);
}
Console.WriteLine("{0}", sortedLastName.Keys[i]);
}
outputLastNames.Close();
}
}