Hi,
I think there is a better way of doing this, instead of implementing a
struct that needs to be carry out with the data just create a class that
implement IComparer. Then you can use Array.Sort with this IComparer.
This is how it will looks:
public class NumberingSorter: IComparer
{
public int Compare(object x, object y)
{
if ( (x== null ) && (y==null) )
return 0;
if ( x == null )
return -1;
if ( y == null )
return 1;
// convert to string
string x1 = x.ToString();
string y1 = y.ToString();
//now split the str
string[] partsX = x1.Split( new char[] { '.' } );
string[] partsY = y1.Split( new char[] { '.' } );
//You should put this on a cycle !!!
if ( partsX[0] > partsY[0] )
return 1;
if ( partsX[0] < partsY[0] )
return -1;
// If they are equal pass to the next one
}
}
Please note that I adapted the above code from another class with a similar
functionality and you will have to refine it, the logic is there though.
Cheers,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Morten Wennevik" <Mo************@hotmail.com> wrote in message
news:opr80kcujeklbvpo@morten_x.edunord...
Hi Dave,
You could create a struct out of a single string for the text and have the
struct implement IComparable. Putting the structs inside any list with a
Sort method should sort it according to your needs.
The CompareTo method will be called on each object to determine if it is
"larger" or "smaller" or "equal" to some other object.
ArrayList list = new ArrayList();
RequirementNumber r = new RequirementNumber();
r.Number = "1.1";
list.Add(r);
r = new RequirementNumber();
r.Number = "1.10";
list.Add(r);
r = new RequirementNumber();
r.Number = "1.2";
list.Add(r);
r = new RequirementNumber();
r.Number = "1.1.1";
list.Add(r);
list.Sort();
The list will now be
1.1
1.1.1
1.2
1.10
If this is not the way you want it sorted, just changed the code to what
you need.
public struct RequirementNumber : IComparable
{
public string Number;
public int CompareTo(object o) // this method will be called by Sort()
{
if(!(o is RequirementNumber))
return -1;
RequirementNumber temp = (RequirementNumber)o;
string[] local = Number.Split(new char[]{'.'});
string[] remote = temp.Number.Split(new char[]{'.'});
int[] numlocal = new int[local.Length];
int[] numremote = new int[remote.Length];
for(int i = 0; i < local.Length; i++)
{
string s = (string)local[i];
try
{
numlocal[i] = Int32.Parse(s);
}
catch
{
numlocal[i] = 0;
}
}
for(int i = 0; i < remote.Length; i++)
{
string s = (string)remote[i];
try
{
numremote[i] = Int32.Parse(s);
}
catch
{
numremote[i] = 0;
}
}
for(int i = 0; i < numlocal.Length; i++)
{
if(numlocal[i] < numremote[i]) // X.1.X < X.2.X
return -1;
else if(numlocal[i] > numremote[i]) // >
return 1;
// else equal and we need to check the next step
if(i == numremote.Length -1) // X.X > X.X.X
return 1;
}
if(numremote.Length > numlocal.Length) // X.X.X < X.X
return -1;
return 0; // numbers are equal
}
}
Happy coding!
Morten Wennevik [C# MVP]