C# 如何将 DataTable 行移动到其 DataTable 的第一个位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13825772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:54:20  来源:igfitidea点击:

How to move a DataTable row to the first position of its DataTable

c#asp.netlinqdatatabledataset

提问by anmarti

I want to get a specific row on an asp.net DataTable and move it to be the first one onto this DataTable base on a column column1value. My Datatable dt1is populated via a DB query and the value to search is via another query from another DB so I don't know the value to search at the dt1 selecttime.

我想在 asp.net DataTable 上获取特定行,并根据列column1值将其移动到此 DataTable 上的第一个行。我的数据表dt1是通过 DB 查询填充的,要搜索的值是通过来自另一个 DB 的另一个查询,所以我dt1 select当时不知道要搜索的值。

// I use this variable to search into
// DataTable
string valueToSearch = "some value";

So I need to search the value some valueinto my DataTable in the column column1. and then move the entire row to the first position.

所以我需要将值搜索some value到列中的 DataTable 中column1。然后将整行移动到第一个位置。

Thank you.

谢谢你。

采纳答案by anmarti

We have to clone the row data before:

我们必须先克隆行数据:

            DataRow[] dr = dtable.Select("column1 ='" + valueToSearch +"'");
            DataRow newRow = dtable.NewRow();
            // We "clone" the row
            newRow.ItemArray = dr[0].ItemArray;
            // We remove the old and insert the new
            ds.Tables[0].Rows.Remove(dr[0]);
            ds.Tables[0].Rows.InsertAt(newRow, 0);

回答by syed mohsin

If the column has only one record for the searched value than try this

如果该列的搜索值只有一条记录,请尝试此操作

DataRow[] dr = dtEmp.Select("column1 ='" + valueToSearch +"'");
myDataTable.Rows.InsertAt(dr[0], 0);

回答by Wonko the Sane

You will have to test the performance on this, but one way to do this is in the query itself. Get the rows that you want at the top first, and combine that with the rest of the rows.

您将不得不对此进行性能测试,但一种方法是在查询本身中进行。首先在顶部获取所需的行,然后将其与其余行合并。

Since I know nothing of your database, here is a generic way to do this:

由于我对您的数据库一无所知,因此这是执行此操作的通用方法:

SELECT Column1, Column2, Column3
FROM MyTable
WHERE Column1 = 'some value'

UNION

SELECT Column1, Column2, Column3
FROM MyTable
WHERE Column1 <> 'some value'