Does filtering a DataTable without a sort parameter preserve original order?

1k Views Asked by At

Per title, if I have a DataTable with columns for ID and Name, pre-sorted by name, and I issue a call such as

    DataRow[] matchingRows = dataTable.Select("ID = " + filterID);

(i.e. without specifying a sort) will my array reliably come back in the table's order?

(And before you ask in comments have you tried it?, I'm not looking for unit-test results that consider every corner case in The Subdivision Escher Built, but documentation/proof that explains expected behavior, since MSFT attempts ain't gettin it done.)

1

There are 1 best solutions below

0
Vince Formica On

If your DataTable has a PrimaryKey then Select will use its index even if your rows aren't sorted that way.

Here is a LinqPad example that demonstrates it.

void Main()
{
            DataTable table = new DataTable("Demo");
            table.Columns.Add("PK", typeof(Int32));
            table.Columns.Add("Sequence", typeof(Int32));

            table.PrimaryKey = new DataColumn[] { table.Columns["PK"] };

            for (int i = 0; i < 10; i++)
            {
                var newRow = table.NewRow();
                newRow["PK"] = 10 - i;
                newRow["Sequence"] = i;
                table.Rows.Add(newRow);
            }

            table.AsEnumerable().Select(x => new { PK = x["PK"], Sequence = x["Sequence"] }).Dump();
            table.Select().Select(x => new { PK = x["PK"], Sequence = x["Sequence"] }).Dump();
}