Questions About Sorting

RogerSchlueter-7899 1,326 Reputation points
2024-08-01T05:38:21.34+00:00

Suppose I have this table in an SQL Server database:

CREATE TABLE Widgets
	(
	WidgetID INT,
	....
	)

and I use this stored procedurre to retrieve the data:

SELECT
		WidgetID
		....
	FROM
		Widgets
	ORDER BY
		WidgetID

In my application I get the data:

Private Sub PopulateWidgets
	Dim Widgets as New List(Of Widget)
	Dim w as Widget
	....
	While rdr.Read
		w = New Widget with
			{
			.WidgetID = rdr.GetInt32(0),
			....
			}
		Widgets.Add(w)
	End While
End Sub

First question: Is Widgets guaranteed to be in sorted order?

Later, I do this:

SomeWidgets = Widgets.While(Function(wdgt) wdgt.Color = Blue)

Second question: Is SomeWidgets still guaranteed to be in sorted order on WidgetID?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,016 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,741 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,376 Reputation points Microsoft Vendor
    2024-08-01T07:23:28.6566667+00:00

    Hi @RogerSchlueter-7899,

    1. Yes, the SQL query you used to retrieve the data includes an ORDER BY WidgetID clause. This means that the data read by the SqlDataReader (rdr) will be sorted by WidgetID, and as you populate the Widgets list in the order read from the reader, the list will remain sorted by WidgetID.
    2. Using the Where method (not While as in your example) to filter Widgets will maintain the order of the original list.
    Dim SomeWidgets = Widgets.Where(Function(wdgt) wdgt.Color = Blue).ToList()
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 45,121 Reputation points
    2024-08-01T06:32:04.8533333+00:00

    If you define a ORDER BY in your query, then it is guaranteed that you get the result in that order sorted.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.