Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in
VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
Fixed(local4 = AddressOf dest(offset))
CType(local4, Short) = CType(src, Short)
Return
End Fixed
What is the "FIXED and END FIXED" and how the syntax error can be "fixed"
???
Thx,
Federico 7 3263
That looks like code that was generated by Reflector. I saw the Fixed
and End Fixed code keywords in Reflector for some code. They don't
exist in VB as far as I know.
Frederico-
If I had to guess, FIXED is some sort of internal notation for "Using",
a new VB.NET 2.0 keyword. You can learn more about the Using keyword here: http://pluralsight.com/blogs/fritz/a...4/28/7834.aspx
Regards-
Eric www.codedaily.com
"Federico G. Babelis" wrote: Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
Fixed(local4 = AddressOf dest(offset))
CType(local4, Short) = CType(src, Short)
Return
End Fixed
What is the "FIXED and END FIXED" and how the syntax error can be "fixed" ???
Thx,
Federico
..NET does not support alphanumeric sort of arrays. (I hope that changes
soon!) Meanwhile, here is a solution.
You could use this in your listbox by sorting the items in an array and then
adding the array items from 0 to length to your listbox.
1. Create a custom comparer class that implements IComparer:
using System;
using System.IO;
namespace Test1CSharp
{
/// <summary>
/// Lacey Orr
/// 29 June 2005
/// Alpha-numeric sorting solution.
/// </summary>
public class AlphaNumCompare : System.Collecti ons.IComparer
{
public int Compare(Object a1, Object b1)
{
//In my case, I compared Directory objects. So I took out
// the filenames / foldernames from the parameter
objects and
// passed those to the sort.
//The string variables to compare
string a = "";
string b = "";
//Is a1 a FileInfo?
if (a1.GetType() == System.Type.Get Type("FileInfo" ))
a = ((FileInfo)a1). Name;
else
a = a1.ToString();
//Is b1 a FileInfo?
if (b1.GetType() == System.Type.Get Type("FileInfo" ))
b = ((FileInfo)b1). Name;
else
b = b1.ToString();
return CompareAlphaNum (a, b);
}
// CompareAlphaNum : Does an alphabetic sort.
private static int CompareAlphaNum (string a, string b)
{
//Do a quick check for empty strings. If one string
is empty, then we
// can get out without doing any work.
if (a.Length == 0 && b.Length > 0)
return -1;
else if (a.Length > 0 && b.Length == 0)
return 1;
else if (a.Length == 0 && b.Length == 0)
return 0;
//The order of chars - make this however you want.
string strNums = "0123456789 ";
string strSortOrder = "
..!#$%&'()*+,-/:;<=>?@[]ˆ_{}~012345678 9ABCDEFGHIJKLMN OPQRSTUVWXYZabc defghijklmnopqr stuvwxyz";
//Variables for comparing
bool aSmaller = true;
bool isFound = false;
int intIndex = 0;
// intLength determines the number of times to loop.
We will loop
// until we hit the end of the shorter string - a
or b.
int intLength = (a.Length < b.Length? a.Length:
b.Length);
string strNumA = "";
string strNumB = "";
int numA = 0;
int numB = 0;
int j = 0;
int k = 0;
//Do the compare while we are not at the end of
either string and haven't found
// the result.
while (!isFound && intIndex < intLength)
{
// if we are dealing with numbers, then sort
the numbers numerically
if (strNums.IndexO f(a[intIndex]) > -1 &&
strNums.IndexOf (b[intIndex]) > -1)
{
//Get all the numbers in string A until
we hit a non-number
j = intIndex;
while (j < a.Length &&
strNums.IndexOf (a[j]) > -1)
{
strNumA += a[j].ToString();
j++;
}
//Get all the numbers in string B until
we hit a non-number
k = intIndex;
while (k < b.Length &&
strNums.IndexOf (b[k]) > -1)
{
strNumB += b[k].ToString();
k++;
}
numA = Convert.ToInt32 (strNumA);
numB = Convert.ToInt32 (strNumB);
if (numA < numB) // a is before b in
sort order; a < b
return -1;
else if (numA > numB) // b is before a
in sort order; a > b
return 1;
else if (numA == numB)
{
//The numbers are the same.
Remove the number part from the strings
// and compare the remainder of
the string.
return
CompareAlphaNum (a.Substring(st rNumA.Length, a.Length-strNumA.Length) ,
b.Substring(str NumB.Length, b.Length-strNumB.Length) );
}
}
else
{
if (strSortOrder.I ndexOf(b[intIndex]) <
strSortOrder.In dexOf(a[intIndex]))
{
// If string a < b in a sort, then
we're done
aSmaller = false;
isFound = true;
}
else if
(strSortOrder.I ndexOf(b[intIndex]) > strSortOrder.In dexOf(a[intIndex]))
{
// If string a > b in a sort, then
we're done
aSmaller = true;
isFound = true;
}
else if (( b.Length < a.Length) &&
(intIndex == intLength - 1))
{
// If the strings are equal up to
the length-th char but a is longer,
// then we're done.
aSmaller = false;
isFound = true;
}
else
{
// Otherwise, keep sorting
intIndex ++;
}
}
}
if ((a.Length == b.Length) && !isFound)
return 0; //strings are the same.
else if (aSmaller)
return -1; // a is before b in sort order; a < b
else
return 1; // b is before a in sort order; ; a b
}
}
}
2. Use the custom class using Array.Sort(myAr ray, new MyCompareClass( )).
a. Add a new web page
b. Add:
using System.IO;
using System.Text;
c. Add a label to the form (lblDir) to display the sort
d. In the page load:
private void Page_Load(objec t sender, System.EventArg s e)
{
//Get files in dir
String strDir = MapPath("~/./");
DirectoryInfo curDir = new DirectoryInfo(s trDir);
FileInfo [] fiArray = curDir.GetFiles ();
string [] strFilenames = new string[fiArray.Length];
for (int j = 0; j < fiArray.Length; j++)
{
strFilenames[j] = fiArray[j].Name;
}
// Sort files
Array.Sort(strF ilenames, new AlphaNumCompare ());
//Display files
StringBuilder sbFiles = new StringBuilder() ;
for (int k = 0; k < strFilenames.Le ngth; k++)
{
sbFiles.Append( strFilenames[k] + "<BR>");
}
lblDir.Text = sbFiles.ToStrin g();
}
Lacey
"Federico G. Babelis" wrote:
Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
Fixed(local4 = AddressOf dest(offset))
CType(local4, Short) = CType(src, Short)
Return
End Fixed
What is the "FIXED and END FIXED" and how the syntax error can be "fixed" ???
Thx,
Federico
Fascinating.
You make the following statement: .NET does not support alphanumeric sort of arrays.
This is simply not true. For your example, you simply have to implement
IComparable for your complex type, you don't need to implement a string
comparison. That is built in.
In other words, you could replace the line: return CompareAlphaNum (a, b);
with
return a.CompareTo(b);
and delete the entire "CompareAlphaNu m" routine.
Note that the CompareAlphaNum routine below doesn't use the same collation
order that .Net uses. Perhaps you meant that .Net doesn't sort a capital
'Z' in front of a lowercase 'a'. If that is what you meant, you are right.
However, it is patently false to say that .Net doesn't support alphanumeric
sorting.
Some reference articles for you to read: http://msdn.microsoft.com/library/en...sorttopic3.asp http://odetocode.com/Articles/203.aspx http://www.devx.com/dotnet/Article/21089 http://aspnet.4guysfromrolla.com/articles/060403-1.aspx
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Lacey" <La***@discussi ons.microsoft.c om> wrote in message
news:11******** *************** ***********@mic rosoft.com... .NET does not support alphanumeric sort of arrays. (I hope that changes soon!) Meanwhile, here is a solution.
You could use this in your listbox by sorting the items in an array and then adding the array items from 0 to length to your listbox.
1. Create a custom comparer class that implements IComparer: using System; using System.IO;
namespace Test1CSharp { /// <summary> /// Lacey Orr /// 29 June 2005 /// Alpha-numeric sorting solution. /// </summary>
public class AlphaNumCompare : System.Collecti ons.IComparer { public int Compare(Object a1, Object b1) { //In my case, I compared Directory objects. So I took out // the filenames / foldernames from the parameter objects and // passed those to the sort.
//The string variables to compare string a = ""; string b = "";
//Is a1 a FileInfo? if (a1.GetType() == System.Type.Get Type("FileInfo" )) a = ((FileInfo)a1). Name; else a = a1.ToString();
//Is b1 a FileInfo? if (b1.GetType() == System.Type.Get Type("FileInfo" )) b = ((FileInfo)b1). Name; else b = b1.ToString();
return CompareAlphaNum (a, b); }
// CompareAlphaNum : Does an alphabetic sort. private static int CompareAlphaNum (string a, string b) { //Do a quick check for empty strings. If one string is empty, then we // can get out without doing any work.
if (a.Length == 0 && b.Length > 0) return -1; else if (a.Length > 0 && b.Length == 0) return 1; else if (a.Length == 0 && b.Length == 0) return 0;
//The order of chars - make this however you want. string strNums = "0123456789 "; string strSortOrder = " .!#$%&'()*+,-/:;<=>?@[]^_{}~0123456789 ABCDEFGHIJKLMNO PQRSTUVWXYZabcd efghijklmnopqrs tuvwxyz";
//Variables for comparing bool aSmaller = true; bool isFound = false; int intIndex = 0; // intLength determines the number of times to loop. We will loop // until we hit the end of the shorter string - a or b. int intLength = (a.Length < b.Length? a.Length: b.Length); string strNumA = ""; string strNumB = ""; int numA = 0; int numB = 0; int j = 0; int k = 0;
//Do the compare while we are not at the end of either string and haven't found // the result. while (!isFound && intIndex < intLength) { // if we are dealing with numbers, then sort the numbers numerically if (strNums.IndexO f(a[intIndex]) > -1 && strNums.IndexOf (b[intIndex]) > -1) { //Get all the numbers in string A until we hit a non-number j = intIndex; while (j < a.Length && strNums.IndexOf (a[j]) > -1) { strNumA += a[j].ToString(); j++; } //Get all the numbers in string B until we hit a non-number k = intIndex; while (k < b.Length && strNums.IndexOf (b[k]) > -1) { strNumB += b[k].ToString(); k++; }
numA = Convert.ToInt32 (strNumA); numB = Convert.ToInt32 (strNumB);
if (numA < numB) // a is before b in sort order; a < b return -1; else if (numA > numB) // b is before a in sort order; a > b return 1; else if (numA == numB) { //The numbers are the same. Remove the number part from the strings // and compare the remainder of the string. return CompareAlphaNum (a.Substring(st rNumA.Length, a.Length-strNumA.Length) , b.Substring(str NumB.Length, b.Length-strNumB.Length) ); } } else { if (strSortOrder.I ndexOf(b[intIndex]) < strSortOrder.In dexOf(a[intIndex])) { // If string a < b in a sort, then we're done aSmaller = false; isFound = true; } else if (strSortOrder.I ndexOf(b[intIndex]) > strSortOrder.In dexOf(a[intIndex])) { // If string a > b in a sort, then we're done aSmaller = true; isFound = true; } else if (( b.Length < a.Length) && (intIndex == intLength - 1)) { // If the strings are equal up to the length-th char but a is longer, // then we're done. aSmaller = false; isFound = true; } else { // Otherwise, keep sorting intIndex ++; } } }
if ((a.Length == b.Length) && !isFound) return 0; //strings are the same. else if (aSmaller) return -1; // a is before b in sort order; a < b else return 1; // b is before a in sort order; ; a b } } }
2. Use the custom class using Array.Sort(myAr ray, new MyCompareClass( )).
a. Add a new web page
b. Add: using System.IO; using System.Text;
c. Add a label to the form (lblDir) to display the sort
d. In the page load:
private void Page_Load(objec t sender, System.EventArg s e) { //Get files in dir String strDir = MapPath("~/./"); DirectoryInfo curDir = new DirectoryInfo(s trDir); FileInfo [] fiArray = curDir.GetFiles (); string [] strFilenames = new string[fiArray.Length]; for (int j = 0; j < fiArray.Length; j++) { strFilenames[j] = fiArray[j].Name; }
// Sort files Array.Sort(strF ilenames, new AlphaNumCompare ());
//Display files StringBuilder sbFiles = new StringBuilder() ; for (int k = 0; k < strFilenames.Le ngth; k++) { sbFiles.Append( strFilenames[k] + "<BR>"); } lblDir.Text = sbFiles.ToStrin g(); }
Lacey
"Federico G. Babelis" wrote:
Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
Fixed(local4 = AddressOf dest(offset))
CType(local4, Short) = CType(src, Short)
Return
End Fixed
What is the "FIXED and END FIXED" and how the syntax error can be "fixed" ???
Thx,
Federico
Hi Nick,
You and I are on two different topics. You are talking about lexographic
sorting (like a dictionary) and I am talking about alphanumeric sorting.
..NET Framework does not support alphanumeric sorting. (I'll prove it. Keep
breathing, Nick! Grab some coffee!)
Let's start with a definition for "alphanumer ic sort": a re-ordering of data
so that numeric and alphabetic data sort as seperate groups. This is unlike
a "lexicograp hic sort" which re-orders data like a dictionary.
I looked through the articles you suggested. In all the examples, the
author either:
1. Compared strings that are completely numeric (for example: (int)"11"
compared to (int)"2")
2. Compared strings that are completely alphabetic (for example: "John"
compared to "Adam")
3. Or, displayed the same problem I solved: http://aspnet.4guysfromrolla.com/dem...tArticles.aspx (See how
"dgExample2.asp x" is listed after "dgExample19.as px"?)
None of these articles address the problem of alphanumeric sorting with
mixed strings like "22Beers" versus "3Beers".
For example, try this with the CompareTo method you suggested:
int intCompare = "22Beers".Compa reTo("3Beers");
PROBLEM: The result is -1, meaning that "22Beers" < "3Beers". If we are
doing an alphabetic comparison, this is correct. But if we are doing an
alphanumeric comparison, this is incorrect because the number 22 is not less
than the number 3.
Let's look at a simple example with an array:
1. Create a web page with three labels (lblOriginal, lblLexo, lblAlphaNum)
2. In the Page_Load:
string[] arrOriginal = {"a3", "a111", "a2", "a1", "a11", "a22"};
for (int i = 0; i < arrOriginal.Len gth; i++ ) lblOriginal.Tex t +=
(arrOriginal[i].ToString() + "<BR>");
string[] arrLexo = {"a3", "a111", "a2", "a1", "a11", "a22"};
Array.Sort(arrL exo);
for (int j = 0; j < arrLexo.Length; j++ ) lblLexo.Text +=
(arrLexo[j].ToString() + "<BR>");
string[] arrAlphaNum = {"a3", "a111", "a2", "a1", "a11", "a22"};
Array.Sort(arrA lphaNum, new AlphaNumCompare ());
for (int k = 0; k < arrAlphaNum.Len gth; k++ ) lblAlphaNum.Tex t +=
(arrAlphaNum[k].ToString() + "<BR>");
3. To the same project as the web page, add the class AlphaNumCompare ()
which implements IComparer (provided in my previous posting).
Run the page, and you'll see the problem.
My original strings:
a3
a111
a2
a1
a11
a22
Microsoft .NET sort:
a1
a11
a111
a2
a22
a3
Custom alphanumeric sort:
a1
a2
a3
a11
a22
a111
See how a11 is before a2 in the Lexographic sort? This is a common problem
- getting string arrays to sort alphanumericall y. I found a lot of postings
from programmers also looking for solutions. For example, if I have an array
of chapter titles for a book, my array needs to sort as:
1.1 Introduction
2.0 Procurement
....
2.9 Department-Specific Accounting
2.10 Delivery Addresses
3.0 Forms
You may want to check out this article from Microsoft which says "The .NET
Framework supports word [culture-sensitive comparison of strings], string
[similar to a word sort, except that there are no special cases], and ordinal
sort [compares the numeric value of each character; for example, a = 65]
rules." Note that it does not have any mention of comparing strings with
both alphabetic and numeric character and treating these character types as
seperate groups: http://msdn.microsoft.com/library/de...classtopic.asp)
I hope Microsoft soon includes support for alphanumeric sorting of strings.
Lacey
"Nick Malik [Microsoft]" wrote: Fascinating.
You make the following statement: .NET does not support alphanumeric sort of arrays.
This is simply not true. For your example, you simply have to implement IComparable for your complex type, you don't need to implement a string comparison. That is built in.
In other words, you could replace the line: return CompareAlphaNum (a, b);
with return a.CompareTo(b);
and delete the entire "CompareAlphaNu m" routine.
Note that the CompareAlphaNum routine below doesn't use the same collation order that .Net uses. Perhaps you meant that .Net doesn't sort a capital 'Z' in front of a lowercase 'a'. If that is what you meant, you are right. However, it is patently false to say that .Net doesn't support alphanumeric sorting.
Some reference articles for you to read: http://msdn.microsoft.com/library/en...sorttopic3.asp http://odetocode.com/Articles/203.aspx http://www.devx.com/dotnet/Article/21089 http://aspnet.4guysfromrolla.com/articles/060403-1.aspx
-- --- Nick Malik [Microsoft] MCSD, CFPS, Certified Scrummaster http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not representative of my employer. I do not answer questions on behalf of my employer. I'm just a programmer helping programmers. -- "Lacey" <La***@discussi ons.microsoft.c om> wrote in message news:11******** *************** ***********@mic rosoft.com... .NET does not support alphanumeric sort of arrays. (I hope that changes soon!) Meanwhile, here is a solution.
You could use this in your listbox by sorting the items in an array and then adding the array items from 0 to length to your listbox.
1. Create a custom comparer class that implements IComparer: using System; using System.IO;
namespace Test1CSharp { /// <summary> /// Lacey Orr /// 29 June 2005 /// Alpha-numeric sorting solution. /// </summary>
public class AlphaNumCompare : System.Collecti ons.IComparer { public int Compare(Object a1, Object b1) { //In my case, I compared Directory objects. So I took out // the filenames / foldernames from the parameter objects and // passed those to the sort.
//The string variables to compare string a = ""; string b = "";
//Is a1 a FileInfo? if (a1.GetType() == System.Type.Get Type("FileInfo" )) a = ((FileInfo)a1). Name; else a = a1.ToString();
//Is b1 a FileInfo? if (b1.GetType() == System.Type.Get Type("FileInfo" )) b = ((FileInfo)b1). Name; else b = b1.ToString();
return CompareAlphaNum (a, b); }
// CompareAlphaNum : Does an alphabetic sort. private static int CompareAlphaNum (string a, string b) { //Do a quick check for empty strings. If one string is empty, then we // can get out without doing any work.
if (a.Length == 0 && b.Length > 0) return -1; else if (a.Length > 0 && b.Length == 0) return 1; else if (a.Length == 0 && b.Length == 0) return 0;
//The order of chars - make this however you want. string strNums = "0123456789 "; string strSortOrder = " .!#$%&'()*+,-/:;<=>?@[]^_{}~0123456789 ABCDEFGHIJKLMNO PQRSTUVWXYZabcd efghijklmnopqrs tuvwxyz";
//Variables for comparing bool aSmaller = true; bool isFound = false; int intIndex = 0; // intLength determines the number of times to loop. We will loop // until we hit the end of the shorter string - a or b. int intLength = (a.Length < b.Length? a.Length: b.Length); string strNumA = ""; string strNumB = ""; int numA = 0; int numB = 0; int j = 0; int k = 0;
//Do the compare while we are not at the end of either string and haven't found // the result. while (!isFound && intIndex < intLength) { // if we are dealing with numbers, then sort the numbers numerically if (strNums.IndexO f(a[intIndex]) > -1 && strNums.IndexOf (b[intIndex]) > -1) { //Get all the numbers in string A until we hit a non-number j = intIndex; while (j < a.Length && strNums.IndexOf (a[j]) > -1) { strNumA += a[j].ToString(); j++; } //Get all the numbers in string B until we hit a non-number k = intIndex; while (k < b.Length && strNums.IndexOf (b[k]) > -1) { strNumB += b[k].ToString(); k++; }
numA = Convert.ToInt32 (strNumA); numB = Convert.ToInt32 (strNumB);
if (numA < numB) // a is before b in sort order; a < b return -1; else if (numA > numB) // b is before a in sort order; a > b return 1; else if (numA == numB) { //The numbers are the same. Remove the number part from the strings // and compare the remainder of the string. return CompareAlphaNum (a.Substring(st rNumA.Length, a.Length-strNumA.Length) , b.Substring(str NumB.Length, b.Length-strNumB.Length) ); } } else { if (strSortOrder.I ndexOf(b[intIndex]) < strSortOrder.In dexOf(a[intIndex])) { // If string a < b in a sort, then we're done aSmaller = false; isFound = true; } else if (strSortOrder.I ndexOf(b[intIndex]) > strSortOrder.In dexOf(a[intIndex])) { // If string a > b in a sort, then we're done aSmaller = true; isFound = true; } else if (( b.Length < a.Length) && (intIndex == intLength - 1)) { // If the strings are equal up to the length-th char but a is longer, // then we're done. aSmaller = false; isFound = true; } else { // Otherwise, keep sorting intIndex ++; } } }
if ((a.Length == b.Length) && !isFound) return 0; //strings are the same. else if (aSmaller) return -1; // a is before b in sort order; a < b else return 1; // b is before a in sort order; ; a b } } }
2. Use the custom class using Array.Sort(myAr ray, new MyCompareClass( )).
a. Add a new web page
b. Add: using System.IO; using System.Text;
c. Add a label to the form (lblDir) to display the sort
d. In the page load:
private void Page_Load(objec t sender, System.EventArg s e) { //Get files in dir String strDir = MapPath("~/./"); DirectoryInfo curDir = new DirectoryInfo(s trDir); FileInfo [] fiArray = curDir.GetFiles (); string [] strFilenames = new string[fiArray.Length]; for (int j = 0; j < fiArray.Length; j++) { strFilenames[j] = fiArray[j].Name; }
// Sort files Array.Sort(strF ilenames, new AlphaNumCompare ());
//Display files StringBuilder sbFiles = new StringBuilder() ; for (int k = 0; k < strFilenames.Le ngth; k++) { sbFiles.Append( strFilenames[k] + "<BR>"); } lblDir.Text = sbFiles.ToStrin g(); }
Lacey
"Federico G. Babelis" wrote:
Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
Fixed(local4 = AddressOf dest(offset))
CType(local4, Short) = CType(src, Short)
Return
End Fixed
What is the "FIXED and END FIXED" and how the syntax error can be "fixed" ???
Thx,
Federico
Thank you for the clarification, Lacey.
I admit that I had not seen the distinction that you are drawing, and I
appreciate the effort you put into describing it. I personally have not run
into this problem, but, by the effort you have gone to describe an answer,
it is clearly important for the applications that you create. I defer to
you on those requirements.
I suppose I would have solved the problems you describe by breaking the
strings up into groups and sorting the groups seperately, which is not
necessarily a better solution. For the kinds of data you are seeing, you
have a good answer.
I do not know if this kind of sorting is specifically "on the plate" for
anyone. If you'd like to see Microsoft implement any feature, I suggest
that you send that description to the MS****@microsof t.com e-mail address.
(perhaps package up your code and the solution below and send it in). You
could also submit an article to a developer magazine to describe your
problem and solution, or create a small project in GotDotNet.com to share
the code. These techniques make it easier for folks to find and reuse your
code than posting on a newsgroup.
Thanks again,
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Lacey" <La***@discussi ons.microsoft.c om> wrote in message
news:CE******** *************** ***********@mic rosoft.com... Hi Nick,
You and I are on two different topics. You are talking about lexographic sorting (like a dictionary) and I am talking about alphanumeric sorting. .NET Framework does not support alphanumeric sorting. (I'll prove it. Keep breathing, Nick! Grab some coffee!)
Let's start with a definition for "alphanumer ic sort": a re-ordering of data so that numeric and alphabetic data sort as seperate groups. This is unlike a "lexicograp hic sort" which re-orders data like a dictionary.
I looked through the articles you suggested. In all the examples, the author either: 1. Compared strings that are completely numeric (for example: (int)"11" compared to (int)"2") 2. Compared strings that are completely alphabetic (for example: "John" compared to "Adam") 3. Or, displayed the same problem I solved: http://aspnet.4guysfromrolla.com/dem...tArticles.aspx (See how "dgExample2.asp x" is listed after "dgExample19.as px"?)
None of these articles address the problem of alphanumeric sorting with mixed strings like "22Beers" versus "3Beers".
For example, try this with the CompareTo method you suggested: int intCompare = "22Beers".Compa reTo("3Beers"); PROBLEM: The result is -1, meaning that "22Beers" < "3Beers". If we are doing an alphabetic comparison, this is correct. But if we are doing an alphanumeric comparison, this is incorrect because the number 22 is not less than the number 3.
Let's look at a simple example with an array: 1. Create a web page with three labels (lblOriginal, lblLexo, lblAlphaNum) 2. In the Page_Load: string[] arrOriginal = {"a3", "a111", "a2", "a1", "a11", "a22"}; for (int i = 0; i < arrOriginal.Len gth; i++ ) lblOriginal.Tex t += (arrOriginal[i].ToString() + "<BR>");
string[] arrLexo = {"a3", "a111", "a2", "a1", "a11", "a22"}; Array.Sort(arrL exo); for (int j = 0; j < arrLexo.Length; j++ ) lblLexo.Text += (arrLexo[j].ToString() + "<BR>");
string[] arrAlphaNum = {"a3", "a111", "a2", "a1", "a11", "a22"}; Array.Sort(arrA lphaNum, new AlphaNumCompare ()); for (int k = 0; k < arrAlphaNum.Len gth; k++ ) lblAlphaNum.Tex t += (arrAlphaNum[k].ToString() + "<BR>");
3. To the same project as the web page, add the class AlphaNumCompare () which implements IComparer (provided in my previous posting).
Run the page, and you'll see the problem. My original strings: a3 a111 a2 a1 a11 a22
Microsoft .NET sort: a1 a11 a111 a2 a22 a3
Custom alphanumeric sort: a1 a2 a3 a11 a22 a111
See how a11 is before a2 in the Lexographic sort? This is a common problem - getting string arrays to sort alphanumericall y. I found a lot of postings from programmers also looking for solutions. For example, if I have an array of chapter titles for a book, my array needs to sort as: 1.1 Introduction 2.0 Procurement ... 2.9 Department-Specific Accounting 2.10 Delivery Addresses 3.0 Forms
You may want to check out this article from Microsoft which says "The .NET Framework supports word [culture-sensitive comparison of strings], string [similar to a word sort, except that there are no special cases], and ordinal sort [compares the numeric value of each character; for example, a = 65] rules." Note that it does not have any mention of comparing strings with both alphabetic and numeric character and treating these character types as seperate groups: http://msdn.microsoft.com/library/de...classtopic.asp)
I hope Microsoft soon includes support for alphanumeric sorting of strings.
Lacey
"Nick Malik [Microsoft]" wrote:
Fascinating.
You make the following statement: > .NET does not support alphanumeric sort of arrays.
This is simply not true. For your example, you simply have to implement IComparable for your complex type, you don't need to implement a string comparison. That is built in.
In other words, you could replace the line: > return CompareAlphaNum (a, b);
with return a.CompareTo(b);
and delete the entire "CompareAlphaNu m" routine.
Note that the CompareAlphaNum routine below doesn't use the same collation order that .Net uses. Perhaps you meant that .Net doesn't sort a capital 'Z' in front of a lowercase 'a'. If that is what you meant, you are right. However, it is patently false to say that .Net doesn't support alphanumeric sorting.
Some reference articles for you to read: http://msdn.microsoft.com/library/en...sorttopic3.asp http://odetocode.com/Articles/203.aspx http://www.devx.com/dotnet/Article/21089 http://aspnet.4guysfromrolla.com/articles/060403-1.aspx
-- --- Nick Malik [Microsoft] MCSD, CFPS, Certified Scrummaster http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not representative of my employer. I do not answer questions on behalf of my employer. I'm just a programmer helping programmers. -- "Lacey" <La***@discussi ons.microsoft.c om> wrote in message news:11******** *************** ***********@mic rosoft.com... > .NET does not support alphanumeric sort of arrays. (I hope that > changes > soon!) Meanwhile, here is a solution. > > You could use this in your listbox by sorting the items in an array and > then > adding the array items from 0 to length to your listbox. > > 1. Create a custom comparer class that implements IComparer: > using System; > using System.IO; > > namespace Test1CSharp > { > /// <summary> > /// Lacey Orr > /// 29 June 2005 > /// Alpha-numeric sorting solution. > /// </summary> > > public class AlphaNumCompare : System.Collecti ons.IComparer > { > public int Compare(Object a1, Object b1) > { > //In my case, I compared Directory objects. So I took > out > // the filenames / foldernames from the parameter > objects and > // passed those to the sort. > > //The string variables to compare > string a = ""; > string b = ""; > > //Is a1 a FileInfo? > if (a1.GetType() == System.Type.Get Type("FileInfo" )) > a = ((FileInfo)a1). Name; > else > a = a1.ToString(); > > //Is b1 a FileInfo? > if (b1.GetType() == System.Type.Get Type("FileInfo" )) > b = ((FileInfo)b1). Name; > else > b = b1.ToString(); > > return CompareAlphaNum (a, b); > } > > // CompareAlphaNum : Does an alphabetic sort. > private static int CompareAlphaNum (string a, string > b) > { > //Do a quick check for empty strings. If one > string > is empty, then we > // can get out without doing any work. > > if (a.Length == 0 && b.Length > 0) > return -1; > else if (a.Length > 0 && b.Length == 0) > return 1; > else if (a.Length == 0 && b.Length == 0) > return 0; > > //The order of chars - make this however you > want. > string strNums = "0123456789 "; > string strSortOrder = " > .!#$%&'()*+,-/:;<=>?@[]^_{}~0123456789 ABCDEFGHIJKLMNO PQRSTUVWXYZabcd efghijklmnopqrs tuvwxyz"; > > //Variables for comparing > bool aSmaller = true; > bool isFound = false; > int intIndex = 0; > // intLength determines the number of times to > loop. > We will loop > // until we hit the end of the shorter > string - > a > or b. > int intLength = (a.Length < b.Length? a.Length: > b.Length); > string strNumA = ""; > string strNumB = ""; > int numA = 0; > int numB = 0; > int j = 0; > int k = 0; > > //Do the compare while we are not at the end of > either string and haven't found > // the result. > while (!isFound && intIndex < intLength) > { > // if we are dealing with numbers, then > sort > the numbers numerically > if (strNums.IndexO f(a[intIndex]) > -1 && > strNums.IndexOf (b[intIndex]) > -1) > { > //Get all the numbers in string A > until > we hit a non-number > j = intIndex; > while (j < a.Length && > strNums.IndexOf (a[j]) > -1) > { > strNumA += a[j].ToString(); > j++; > } > //Get all the numbers in string B > until > we hit a non-number > k = intIndex; > while (k < b.Length && > strNums.IndexOf (b[k]) > -1) > { > strNumB += b[k].ToString(); > k++; > } > > numA = Convert.ToInt32 (strNumA); > numB = Convert.ToInt32 (strNumB); > > if (numA < numB) // a is before b in > sort order; a < b > return -1; > else if (numA > numB) // b is before > a > in sort order; a > b > return 1; > else if (numA == numB) > { > //The numbers are the same. > Remove the number part from the strings > // and compare the > remainder > of > the string. > return > CompareAlphaNum (a.Substring(st rNumA.Length, a.Length-strNumA.Length) , > b.Substring(str NumB.Length, b.Length-strNumB.Length) ); > } > } > else > { > if > (strSortOrder.I ndexOf(b[intIndex]) < > strSortOrder.In dexOf(a[intIndex])) > { > // If string a < b in a sort, > then > we're done > aSmaller = false; > isFound = true; > } > else if > (strSortOrder.I ndexOf(b[intIndex]) > strSortOrder.In dexOf(a[intIndex])) > { > // If string a > b in a sort, > then > we're done > aSmaller = true; > isFound = true; > } > else if (( b.Length < a.Length) && > (intIndex == intLength - 1)) > { > // If the strings are equal up > to > the length-th char but a is longer, > // then we're done. > aSmaller = false; > isFound = true; > } > else > { > // Otherwise, keep sorting > intIndex ++; > } > } > } > > if ((a.Length == b.Length) && !isFound) > return 0; //strings are the same. > else if (aSmaller) > return -1; // a is before b in sort order; > a > < b > else > return 1; // b is before a in sort order; > ; a >> b > } > } > } > > > 2. Use the custom class using Array.Sort(myAr ray, new > MyCompareClass( )). > > a. Add a new web page > > b. Add: > using System.IO; > using System.Text; > > c. Add a label to the form (lblDir) to display the sort > > d. In the page load: > > private void Page_Load(objec t sender, System.EventArg s e) > { > //Get files in dir > String strDir = MapPath("~/./"); > DirectoryInfo curDir = new DirectoryInfo(s trDir); > FileInfo [] fiArray = curDir.GetFiles (); > string [] strFilenames = new string[fiArray.Length]; > for (int j = 0; j < fiArray.Length; j++) > { > strFilenames[j] = fiArray[j].Name; > } > > // Sort files > Array.Sort(strF ilenames, new AlphaNumCompare ()); > > //Display files > StringBuilder sbFiles = new StringBuilder() ; > for (int k = 0; k < strFilenames.Le ngth; k++) > { > sbFiles.Append( strFilenames[k] + "<BR>"); > } > lblDir.Text = sbFiles.ToStrin g(); > } > > Lacey > > "Federico G. Babelis" wrote: > >> Hi All: >> >> I have this line of code, but the syntax check in VB.NET 2003 and also >> in >> VB.NET 2005 Beta 2 shows as unknown: >> >> Dim local4 As Byte >> >> Fixed(local4 = AddressOf dest(offset)) >> >> CType(local4, Short) = CType(src, Short) >> >> Return >> >> End Fixed >> >> What is the "FIXED and END FIXED" and how the syntax error can be >> "fixed" >> ??? >> >> Thx, >> >> Federico >> >> >>
On Wed, 13 Jul 2005 12:51:01 -0700, Lacey wrote: You and I are on two different topics. You are talking about lexographic sorting (like a dictionary) and I am talking about alphanumeric sorting. .NET Framework does not support alphanumeric sorting. (I'll prove it. Keep breathing, Nick! Grab some coffee!)
[snip]
You've demonstrated what you mean admirably. The problem is that the exact
phrase "alphanumer ic sorting" is not frequently used to represent the type
of problem you have solved. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: hokiegal99 |
last post by:
A few questions about the following code. How would I "wrap" this in a
function, and do I need to?
Also, how can I make the code smart enough to realize that when a file
has 2 or more bad charcters in it, that the code needs to run until all
bad characters are gone? For example, if a file has the name
"<bad*mac\file" the program has to run 3 times to get all three bad
chars out of the file name.
The passes look like this:
|
by: David MacQuigg |
last post by:
I'm not getting any feedback on the most important benefit in my
proposed "Ideas for Python 3" thread - the unification of methods and
functions. Perhaps it was buried among too many other less important
changes, so in this thread I would like to focus on that issue alone.
I have edited the Proposed Syntax example below to take out the
changes unecessary to this discussion. I left in the change of
"instance variable" syntax (...
|
by: Rubén Campos |
last post by:
I haven't found any previous message related to what I'm going to ask here,
but accept my anticipated excuses if I'm wrong.
I want to ask about the real usefulness of the 'inline' keyword. I've read
many authors (and it's my belief, too) who discourage the use of the
'inline' keyword, because:
- The 'inline' word only advice the compiler about wich functions should be
expanded, but not force it to expand them. Also, the compiler can...
|
by: cwdjrxyz |
last post by:
Javascript has a very small math function list. However there is no
reason that this list can not be extended greatly. Speed is not an
issue, unless you nest complicated calculations several levels deep. In
that case you need much more ram than a PC has to store functions
calculated in loops so that you do not have to recalculate every time
you cycle through the nest of loops. Using a HD for storage to extend
ram is much too slow for many...
|
by: Bryan Olson |
last post by:
The current Python standard library provides two cryptographic
hash functions: MD5 and SHA-1 . The authors of MD5 originally
stated:
It is conjectured that it is computationally infeasible to
produce two messages having the same message digest.
That conjecture is false, as demonstrated by Wang, Feng, Lai and
Yu in 2004 . Just recently, Wang, Yu, and Lin showed a short-
cut solution for finding collisions in SHA-1 . Their result
| |
by: Tim ffitch |
last post by:
Hi
I have created a VB dll file that contains common functions I use
across various projects in VB, Access and Excel. Rather than have to
code the functions in each I decided to use the dll route.
The problem being that I can't call these functions from the query
designer in Access. I decided that I would try the route of declaring
the functions from the dll file the same way you would for the Windows
API. Access then complains that...
|
by: Timothy Madden |
last post by:
Hello all.
I program C++ since a lot of time now and I still don't know this simple
thing: what's the problem with local functions so they are not part of
C++ ?
There surely are many people who will find them very helpfull. gcc has
them as a non-standard option, but only when compiling C language code,
so I'm afraid there might be some obscure reason why local functions are
not so easy to be dealt with in C++, which I do not yet know.
|
by: v4vijayakumar |
last post by:
Why we need "virtual private member functions"? Why it is not an
(compile time) error?
|
by: Immortal Nephi |
last post by:
My project grows large when I put too many member functions into one
class. The header file and source code file will have approximately
50,000 lines when one class contains thousand member functions. Is it
normal how C++ Compiler can compile large class without any problem?
Didn't C++ Compiler have rules to limit the number of member
functions?
One big object has complex operations how member variables and member
functions can be...
|
by: KevinADC |
last post by:
This snippet of code provides several examples of programming techniques that can be applied to most programs.
using hashes to create unique results
static variable
recursive function
serialization
The code itself generates a list of strings comprised of random numbers. No number will be repeated within a string, and no string will be repeated within the list of strings. Following the code is a brief discussion of how the above...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |