473,668 Members | 2,616 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting strings as numeric

Hello,
Is there a simple way to sort a listbox that contains strings that are
numbers?
My listbox is populated from a database field that has a datatype of string,
but typically contains numbers.
(I need to keep them as strings because occasionally they will have a letter
after them - 1a for ex).
I don't want zeros in front of them, I just want them to sort like this:
1
2
10
11
20
instead of 1
10
11
2
20

Possible??
Thanks in advance.
Amber

Nov 22 '05 #1
6 5919
Hi Amber,

You can do this easily by creating your own sorting rules, and in your case it is very simple.
It may even be possible to implement this in a databinding although I'm not sure how.
string[] strings = new string[]{
"1",
"10",
"11",
"2",
"20"
};

Array.Sort(stri ngs, new MyComparer());
listBox1.AddRan ge(strings);

....

public class MyComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
// strip away any trailing letters
// for instance, if nx.CompareTo(ny ) returns 0,
// then compare the trailing letters using string.CompareT o
int nx = Int32.Parse((st ring)x);
int ny = Int32.Parse((st ring)y);
return nx.CompareTo(ny );
}
catch
{
return 0;
}
}
}
On Thu, 26 May 2005 18:58:09 +0200, amber <am***@discussi ons.microsoft.c om> wrote:
Hello,
Is there a simple way to sort a listbox that contains strings that are
numbers?
My listbox is populated from a database field that has a datatype of string,
but typically contains numbers.
(I need to keep them as strings because occasionally they will have a letter
after them - 1a for ex).
I don't want zeros in front of them, I just want them to sort like this:
1
2
10
11
20
instead of 1
10
11
2
20

Possible??
Thanks in advance.
Amber


--
Happy coding!
Morten Wennevik [C# MVP]
Nov 22 '05 #2
Hi Amber,

You can do this easily by creating your own sorting rules, and in your case it is very simple.
It may even be possible to implement this in a databinding although I'm not sure how.
string[] strings = new string[]{
"1",
"10",
"11",
"2",
"20"
};

Array.Sort(stri ngs, new MyComparer());
listBox1.AddRan ge(strings);

....

public class MyComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
// strip away any trailing letters
// for instance, if nx.CompareTo(ny ) returns 0,
// then compare the trailing letters using string.CompareT o
int nx = Int32.Parse((st ring)x);
int ny = Int32.Parse((st ring)y);
return nx.CompareTo(ny );
}
catch
{
return 0;
}
}
}
On Thu, 26 May 2005 18:58:09 +0200, amber <am***@discussi ons.microsoft.c om> wrote:
Hello,
Is there a simple way to sort a listbox that contains strings that are
numbers?
My listbox is populated from a database field that has a datatype of string,
but typically contains numbers.
(I need to keep them as strings because occasionally they will have a letter
after them - 1a for ex).
I don't want zeros in front of them, I just want them to sort like this:
1
2
10
11
20
instead of 1
10
11
2
20

Possible??
Thanks in advance.
Amber


--
Happy coding!
Morten Wennevik [C# MVP]
Nov 22 '05 #3
The simplest solution solution I see would be to use two separate fields.
Server side you'll use ORDER BY num,letter to get the correct order...
Especially it"s worth to consider if the letter has some kind of meaning you
may want also to exploit at some other place(s).

Else you'll have to "process" these entries before sorting them (such as
ordering on a computed field that uses leading 0s for example by using ORDER
BY RIGHT("0000"+Fi eld,4) or something similar depending on your DB (and for
example it won't use indexing etc...)

Patrice
--

"amber" <am***@discussi ons.microsoft.c om> a écrit dans le message de
news:82******** *************** ***********@mic rosoft.com...
Hello,
Is there a simple way to sort a listbox that contains strings that are
numbers?
My listbox is populated from a database field that has a datatype of string, but typically contains numbers.
(I need to keep them as strings because occasionally they will have a letter after them - 1a for ex).
I don't want zeros in front of them, I just want them to sort like this:
1
2
10
11
20
instead of 1
10
11
2
20

Possible??
Thanks in advance.
Amber

Nov 22 '05 #4
The simplest solution solution I see would be to use two separate fields.
Server side you'll use ORDER BY num,letter to get the correct order...
Especially it"s worth to consider if the letter has some kind of meaning you
may want also to exploit at some other place(s).

Else you'll have to "process" these entries before sorting them (such as
ordering on a computed field that uses leading 0s for example by using ORDER
BY RIGHT("0000"+Fi eld,4) or something similar depending on your DB (and for
example it won't use indexing etc...)

Patrice
--

"amber" <am***@discussi ons.microsoft.c om> a écrit dans le message de
news:82******** *************** ***********@mic rosoft.com...
Hello,
Is there a simple way to sort a listbox that contains strings that are
numbers?
My listbox is populated from a database field that has a datatype of string, but typically contains numbers.
(I need to keep them as strings because occasionally they will have a letter after them - 1a for ex).
I don't want zeros in front of them, I just want them to sort like this:
1
2
10
11
20
instead of 1
10
11
2
20

Possible??
Thanks in advance.
Amber

Nov 22 '05 #5


amber wrote:
I don't want zeros in front of them, I just want them to sort like this:
1
2
10 Possible??


Write an IComparer. Here is one (untested, from memory) that works
nicely on string-representations with other radix'es than 10:

class NumericStringCo mparer: IComparer {
public bool IgnoreCase = true;
// Some cultures sorts wierdly on i.e. "AA"
public System.Globaliz ation.CultureIn fo Culture =
System.Globaliz ation.CultureIn fo.InvariantCul ture;
´ public int Compare(object x, object y) {
string s1 = (string)x;
string s2 = (string)y;
int l1 = s1.Length;
int l2 = s2.Length;
if ( l1 == l2 )
return string.Compare(
s1, 0, s2, 0, l1,
IgnoreCase,
Culture);
else
return l1 - l2;
}
}

This is a usefull class on it's own but does not solve the problem, for
that I normally use a "column-sorter", roughly like:

class ColumnSorter: IComparer {
public int Column;
IComparer Comparer;
public ColumnSorter(IC omparer comparer, int column) {
this.Column = column;
this.Comparer = comparer;
}
public int Compare(object x, object y) {
return Comparer.Compar e(
((ListViewItem) x).SubItems[Column].Text,
((ListViewItem) y).SubItems[Column].Text);
}
}

Which you can attach to the ListView using .ListViewItemSo rter. It
allows you to change which column to sort by assigning to .Column.

There may be some null-value-checking required, I can't remember that
off the top of my head.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 22 '05 #6


amber wrote:
I don't want zeros in front of them, I just want them to sort like this:
1
2
10 Possible??


Write an IComparer. Here is one (untested, from memory) that works
nicely on string-representations with other radix'es than 10:

class NumericStringCo mparer: IComparer {
public bool IgnoreCase = true;
// Some cultures sorts wierdly on i.e. "AA"
public System.Globaliz ation.CultureIn fo Culture =
System.Globaliz ation.CultureIn fo.InvariantCul ture;
´ public int Compare(object x, object y) {
string s1 = (string)x;
string s2 = (string)y;
int l1 = s1.Length;
int l2 = s2.Length;
if ( l1 == l2 )
return string.Compare(
s1, 0, s2, 0, l1,
IgnoreCase,
Culture);
else
return l1 - l2;
}
}

This is a usefull class on it's own but does not solve the problem, for
that I normally use a "column-sorter", roughly like:

class ColumnSorter: IComparer {
public int Column;
IComparer Comparer;
public ColumnSorter(IC omparer comparer, int column) {
this.Column = column;
this.Comparer = comparer;
}
public int Compare(object x, object y) {
return Comparer.Compar e(
((ListViewItem) x).SubItems[Column].Text,
((ListViewItem) y).SubItems[Column].Text);
}
}

Which you can attach to the ListView using .ListViewItemSo rter. It
allows you to change which column to sort by assigning to .Column.

There may be some null-value-checking required, I can't remember that
off the top of my head.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 22 '05 #7

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

Similar topics

2
5244
by: xyz | last post by:
I am trying to sort a string array. I am trying to use a collator class, but I get errors. Do I need to an "import" statement or something? I would appreciate your suggestions. /javadev/com/azdictpkg/PhraseList.java:60: cannot resolve symbol symbol : class Collator
3
412
by: amber | last post by:
Hello, Is there a simple way to sort a listbox that contains strings that are numbers? My listbox is populated from a database field that has a datatype of string, but typically contains numbers. (I need to keep them as strings because occasionally they will have a letter after them - 1a for ex). I don't want zeros in front of them, I just want them to sort like this: 1 2
3
1922
by: Daniel Weinand | last post by:
hello ng, i have a problem and a imho an insufficient method of solution. strings should be sorted by specific text pattern and dispayed in groups. the strings are stored in a db and have the following layout: 1.0.0.0 1.1.0.0 1.1.1.0 1.1.2.0
3
1968
by: melanieab | last post by:
Hi, When you click on a column header to sort in ascending or descending order, numbers (and dates) aren't sorted correctly. It turns up like this: 1 10 11 2 3 4
1
1440
by: | last post by:
I'm querying Index Server to return search results, both regular properties and some custom properties I've created. Index Server has this preference for thinking about information as strings rather than datatypes.If you really work at it, you can configure Index Server to treat the data as, say, sortable DateTime datatypes, or integer datatypes. But I'm finding this a huge pain in the butt, and it bothers me that I'm attaching a bunch of...
8
8842
by: DierkErdmann | last post by:
Hi ! I know that this topic has been discussed in the past, but I could not find a working solution for my problem: sorting (lists of) strings containing special characters like "ä", "ü",... (german umlaute). Consider the following list: l = For sorting the letter "Ä" is supposed to be treated like "Ae", therefore sorting this list should yield
3
2185
by: SneakyElf | last post by:
i am very green with c++ so i get stuck on very simple things anyway, i need to write a program that would read data from file (containing names of tv shows and their networks) one line at a time ( ; separates tv show and network) sort the strings according to the network and according to the show. and so: //to open file - ifstream myFile;
1
3050
AMT India
by: AMT India | last post by:
I am having a list of countries, among which some of them starts with German special characters ( like Umplot). I want to sort the list independent of this German characters. So that Umplot will come after "t" in English alphabet. Thanx in advance,
4
2433
by: Holger | last post by:
I tried to do this elegantly, but did not come up with a good solution Sort strings like foo1bar2 foo10bar10 foo2bar3 foo10bar2 So that they come out: foo1bar2
0
8459
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
8367
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,...
0
8889
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
8790
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
8570
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
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
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.