473,395 Members | 1,539 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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 5900
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(strings, new MyComparer());
listBox1.AddRange(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.CompareTo
int nx = Int32.Parse((string)x);
int ny = Int32.Parse((string)y);
return nx.CompareTo(ny);
}
catch
{
return 0;
}
}
}
On Thu, 26 May 2005 18:58:09 +0200, amber <am***@discussions.microsoft.com> 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(strings, new MyComparer());
listBox1.AddRange(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.CompareTo
int nx = Int32.Parse((string)x);
int ny = Int32.Parse((string)y);
return nx.CompareTo(ny);
}
catch
{
return 0;
}
}
}
On Thu, 26 May 2005 18:58:09 +0200, amber <am***@discussions.microsoft.com> 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"+Field,4) or something similar depending on your DB (and for
example it won't use indexing etc...)

Patrice
--

"amber" <am***@discussions.microsoft.com> a écrit dans le message de
news:82**********************************@microsof t.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"+Field,4) or something similar depending on your DB (and for
example it won't use indexing etc...)

Patrice
--

"amber" <am***@discussions.microsoft.com> a écrit dans le message de
news:82**********************************@microsof t.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 NumericStringComparer: IComparer {
public bool IgnoreCase = true;
// Some cultures sorts wierdly on i.e. "AA"
public System.Globalization.CultureInfo Culture =
System.Globalization.CultureInfo.InvariantCulture;
´ 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(IComparer comparer, int column) {
this.Column = column;
this.Comparer = comparer;
}
public int Compare(object x, object y) {
return Comparer.Compare(
((ListViewItem)x).SubItems[Column].Text,
((ListViewItem)y).SubItems[Column].Text);
}
}

Which you can attach to the ListView using .ListViewItemSorter. 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 NumericStringComparer: IComparer {
public bool IgnoreCase = true;
// Some cultures sorts wierdly on i.e. "AA"
public System.Globalization.CultureInfo Culture =
System.Globalization.CultureInfo.InvariantCulture;
´ 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(IComparer comparer, int column) {
this.Column = column;
this.Comparer = comparer;
}
public int Compare(object x, object y) {
return Comparer.Compare(
((ListViewItem)x).SubItems[Column].Text,
((ListViewItem)y).SubItems[Column].Text);
}
}

Which you can attach to the ListView using .ListViewItemSorter. 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
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. ...
3
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....
3
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...
3
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
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...
8
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 "ä", "ü",......
3
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...
1
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...
4
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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,...
0
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...
0
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...
0
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...

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.