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

  • Thread starter Thread starter John Dalberg
  • Start date Start date
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
 
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 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
 
Back
Top