按特定列而不是主键对 DataTable 进行排序

Sort a DataTable by a specific column rather than the primary key

我是 C# 的新手,我正在尝试 link 我的 Access 数据库到程序并对其进行操作,然后将其写入文本文件。

但是,我的数据目前是根据 ID(这是主键)排序的。 我想根据姓氏对其进行排序,然后进行操作,因为当我使用 "foreach(DataRow drr in dra)" 时,行是按 ID 的顺序检索的。

[dra->数据行]

我想在排序后访问这些行,但我不确定该怎么做。以下是我的代码。

OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn11);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

myAccessConn11.Open();
myDataAdapter.Fill(myDataSet, "Personal_Data");
myAccessConn11.Close();

DataTableCollection dta = myDataSet.Tables;
DataRowCollection dra = myDataSet.Tables["Personal_Data"].Rows;

foreach (DataRow drr in dra)
{
    *Manipulation*
}

我尝试使用 myDataSet.Tables["Personal_Data"].DefaultView.Sort = "LastName DESC"; 但它没有用。

在访问 table 中的行之前,还有其他方法可以对它们进行排序吗?

提前致谢!

您可以对 "strAccessSelect" SQL 查询中的行进行排序,例如:

SELECT Id, FirstName, LastName from MyTable ORDER BY LastName ASC;