Values in List<int> getting sorted.. why?

J

John Dalberg

I am adding integer values from a datarow collection to a List<int> using
the Add method. The values are read in the correct order from the
collection but once the List is populated, the values in the List are
sorted in ascending order. Why? This
is undesirable.

John Dalberg
 
G

greg.merideth

I just tried out a code snippet like this and my generic list remains
unsorted until I called Sort() on the list. Are you sure that the data
is coming back from your query unsorted or that you are not using a
sorted list to begin with?

This fills a list unsorted, prints it, sorts it then prints again
sorted.

Random r = new Random();
List<int> ul = new List<int>();
for(int i = 0; i < 100; ++i) ul.Add(r.Next(1, 100));
foreach(int i in ul) Console.Write("{0} ", i);
ul.Sort();
Console.WriteLine();
foreach(int i in ul) Console.Write("{0} ", i);
 
J

John Dalberg

I just tried out a code snippet like this and my generic list remains
unsorted until I called Sort() on the list. Are you sure that the data
is coming back from your query unsorted or that you are not using a
sorted list to begin with?

This fills a list unsorted, prints it, sorts it then prints again
sorted.

Random r = new Random();
List<int> ul = new List<int>();
for(int i = 0; i < 100; ++i) ul.Add(r.Next(1, 100));
foreach(int i in ul) Console.Write("{0} ", i);
ul.Sort();
Console.WriteLine();
foreach(int i in ul) Console.Write("{0} ", i);

I did some more investigation and I found out that I needed to add a sort
to my datatable select method even though the original sql query had an
order by.

Thanks for your help.

John Dalberg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top