using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO;
namespace WindowsFormsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { // Holds the list from the file List<String> dataSorted = new List<string>(); // Read the lines from the file StreamReader sr = new StreamReader("Data.txt"); while (!sr.EndOfStream) { // insert line into list dataSorted.Add(sr.ReadLine()); } // Sort the list with a custom compare dataSorted.Sort(AddressCompare);
// Display the list to the console window or write to file foreach( String data in dataSorted ) { Console.WriteLine(data); } }
int AddressCompare(object x, object y) { // Two null objects are equal if (x == null && y == null) return 0; //Any object that is not null is greater then an object that is null if (x == null) return -1; if (y == null) return 1;
// CheckBox to see that both objects are Strings if (!(x.GetType() == typeof(String) && y.GetType() == typeof(String))) { throw new ArgumentException("Can't compare " + x.GetType().ToString() + "/" + y.GetType().ToString()); }
// Parse the string to get the address String[] addr = new String[2]; String[] type = new String[2]; type[0] = x.ToString().Substring(0, 2); type[1] = y.ToString().Substring(0, 2); for (int idx = 0; idx < 2; idx++) { // Not sure how long the address field is so I added all the types given in the // you will need to modify the length of the address for each type element 0 is // the x string and element 1 is the y string. switch (type[idx]) { case "S0": if (idx == 0) { addr[0] = x.ToString().Substring(4, 6); } else { addr[1] = y.ToString().Substring(4, 6); } break; case "S3": if (idx == 0) { addr[0] = x.ToString().Substring(4, 6); } else { addr[1] = y.ToString().Substring(4, 6); } break; case "S5": if (idx == 0) { addr[0] = x.ToString().Substring(4, 6); } else { addr[1] = y.ToString().Substring(4, 6); } break; case "S7": if (idx == 0) { addr[0] = x.ToString().Substring(4, 6); } else { addr[1] = y.ToString().Substring(4, 6); } break; } } // Convert hex string to integer int[] key = new int[2]; key[0] = int.Parse(addr[0], System.Globalization.NumberStyles.HexNumber); key[1] = int.Parse(addr[1], System.Globalization.NumberStyles.HexNumber);
// compare integer values if (key[0] == key[1]) return 0; if (key[0] < key[1]) return -1; return 1; } } } |
No comments:
Post a Comment