473,806 Members | 2,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array.Sort not sorting by character code value?

Why does the code below output this:
"v a" (118,32,97)
"w a" (119,32,97)
"v b" (118,32,98)
"w b" (119,32,98)
"v c" (118,32,99)
"w c" (119,32,99)

and not this (as one would expect if Array.Sort sorted by character
code value):
"v a" (118,32,97)
"v b" (118,32,98)
"v c" (118,32,99)
"w a" (119,32,97)
"w b" (119,32,98)
"w c" (119,32,99)
Is there any way to make Array.Sort sort strings by character code
value?

---------------------------

string[] strings = new string[] {
"w b",
"v a",
"v c",
"w a",
"v b",
"w c"
};

Array.Sort(stri ngs);
PrintStrings(st rings);

private void PrintStrings(st ring[] strings)
{
for (int i=0; i<strings.Lengt h; i++)
{
Console.WriteLi ne(String.Forma t(" \"{0}\" ({1})",
strings[i],
GetASCIICharCod es(strings[i])));
}
}

private string GetASCIICharCod es(string s)
{
StringBuilder sb = new StringBuilder() ;

for (int i=0; i<s.Length; i++)
{
char c = Convert.ToChar( s.Substring(i, 1));

sb.Append(Strin g.Format("{0}{1 }",
((int)c).ToStri ng(),
i<s.Length-1 ? "," : ""));
}

return sb.ToString();
}

Thanks,
Niklas Uhlin

Nov 17 '05 #1
3 2740
Hello,
Array.Sort(myAr ray) method uses default comparer to compare objects. It
gets comparer as Comparer.Defaul t which is a comparer associated with
the Thread.CurrentC ulture of the current thread. So it depends on the
current culture how does it behave in this scenario.
I have run your code and it displayed the strings in your desired
format.

Cheers :)
Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #2
Hi Niklas,

As Maqsood said, it is probably caused by your current culture.
As an example, for me, trying to sort the strings

"aaa"
"bbb"
"ccc"

I end up with

"bbb"
"ccc"
"aaa"

because 'aa' in a surname is pronounced as 'å' the last character in the Norwegian alphabet.

Hopefully we will be able to turn off or at least change this behaviour, without having to change culture, in Windows Longhorn.
Similarly you may encountere 'smart sorting' especially for numbers where
"12"
"1A"
is sorted as
"1A"
"12"

because Microsoft has decided that humans in general expect it that way and does not see numeric characters as characters, but numbers and completely different from other characters.

http://blogs.msdn.com/michkap/archiv...05/346933.aspx

At least you can turn off this behaviour using TweakUI

http://blogs.msdn.com/michkap/archiv...01/404830.aspx

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #3
Array.Sort(stri ngs, new Comparer(new
System.Globaliz ation.CultureIn fo("sv-SE"))); // Swedish
.... produces the same error.
This is wierd because V comes before W in the swedish alphabet, so one
would think that sorting with a swedish CultureInfo would produce a
correct result.

If I on the other hand use
Array.Sort(mySt ringArray, new
Comparer(System .Globalization. CultureInfo.Inv ariantCulture)) ;
.... it works.

Thanks alot for the help!

Brgds,
Niklas Uhlin

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
17610
by: lawrence | last post by:
Is there an easy way to sort a 2 dimensional array alphabetically by the second field in each row? Also, when I use sort() on a two dimensional array, it seems to work a lot like array_reverse(). Can anyone tell me why?
1
6419
by: LRW | last post by:
I have a page that's doing a search of a database, create an array and displays it. And I have it displaying the array just fine, but when I try to sort it, I get the error: Warning: sort() expects parameter 1 to be array, null given in /home/iestud/public_html/gto/search.php on line 43 (line 43 is the sort() function). Here's the page--go to: http://gto.ie-studios.net/item.php?itemid=3
7
3270
by: Federico G. Babelis | last post by:
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)
4
2549
by: John Bullock | last post by:
Hello, I am at wit's end with an array sorting problem. I have a simple table-sorting function which must, at times, sort on columns that include entries with nothing but a space (@nbsp;). I want all of the spaces to be put in the first slots of the array. IE 6 does this. But Firefox 0.9.1 doesn't, and I don't know why. I have not been able to reproduce it in very simple form (which is itself a puzzle). But example code is...
3
6413
by: SilverWolf | last post by:
I need some help with sorting and shuffling array of strings. I can't seem to get qsort working, and I don't even know how to start to shuffle the array. Here is what I have for now: #include <stdio.h> void main(void) { char lines; int count = 0, i;
21
3229
by: yeti349 | last post by:
Hi, I'm using the following code to retrieve data from an xml file and populate a javascript array. The data is then displayed in html table form. I would like to then be able to sort by each column. Once the array elements are split, what is the best way to sort them? Thank you. //populate data object with data from xml file. //Data is a comma delimited list of values var jsData = new Array(); jsData = {lib: "#field...
9
2617
by: Dylan Parry | last post by:
Hi folks, I have a database that contains records with IDs like "H1, H2, H3, ..., Hn" and these refer to local government policy numbers. For example, H1 might be "Housing Policy 1" and so on. For some more insight, not all policies will be prefixed with an "H", an in fact they could be prefixed with *any* letter combination, but they will always end with a number. When I retrieve them from the database I use "ORDER BY id" to get them...
16
2568
by: randallc | last post by:
Hi, I need to take an input of 1D array, each item pipe delimited, and make a 2D array for column sorting.. Can anyone please help as my first ady with jscript, and haven't a clue why i get this error; I thought I was using other scripts exactly?!... var list = ; WScript.Echo(list.join("\n")); WScript.Echo(list); //~ myarray.sort(mysortfn); ListSorted=SortArray(list); WScript.Echo(ListSorted.join("\n"));
152
9935
by: vippstar | last post by:
The subject might be misleading. Regardless, is this code valid: #include <stdio.h> void f(double *p, size_t size) { while(size--) printf("%f\n", *p++); } int main(void) { double array = { { 3.14 }, { 42.6 } }; f((double *)array, sizeof array / sizeof **array); return 0;
0
9719
marktang
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...
0
10620
Oralloy
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...
0
10369
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10372
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10110
tracyyun
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...
1
7650
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6877
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();...
1
4329
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
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.