473,385 Members | 1,844 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,385 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 5899
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.