C# 根据条件从数据表中删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17841099/
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 10:38:30  来源:igfitidea点击:

Remove Row from DataTable Depending on Condition

c#asp.net

提问by Apollo

I have a List that holds some IDs. I want to remove the rows from a DataTable where = ListLinkedIds

我有一个包含一些 ID 的列表。我想从 DataTable 中删除行,其中 = ListLinkedIds

List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
DataSet ds = new DataSet();
SqlDataAdapter da = null;
DataTable dt = new DataTable();



    da = new SqlDataAdapter("SELECT TicketID, DisplayNum, TranstypeDesc, SubQueueId, EstimatedTransTime,LinkedTicketId FROM vwQueueData WHERE (DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND QueueId = @QueueId AND SubQueueId = @SubQueueId   AND LinkedTicketId != @LinkedTicketId  AND Called IS NULL", cs);
   da.SelectCommand.Parameters.AddWithValue("@QueueId", Queue);
   da.SelectCommand.Parameters.AddWithValue("@SubQueueId", SubQueue);
   da.SelectCommand.Parameters.AddWithValue("@LinkedTicketId", ListLinkedIds[x]);
   da.Fill(ds);


//Removes from DataTable 
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
   //Remove Row from DataTable Where ListLinkedIds[x]
}


gvMain.DataSource = ds;
gvMain.DataBind();

I tried dt.Rows.RemoveAt(remove) but that removes only the row number. I want to remove every row that is in the ListLinkedIds.

我试过 dt.Rows.RemoveAt(remove) 但这仅删除了行号。我想删除 ListLinkedIds 中的每一行。

采纳答案by Habib

Using LINQ you can create a new DataTablelike:

使用 LINQ,您可以创建一个新的DataTable像:

DataTable newDataTable = dt.AsEnumerable()
                        .Where(r=> !ListLinkedIds.Contains(r.Field<string>("IDCOLUMN")))
                        .CopyToDataTable();

回答by Ted

You can select the rows and then remove the returned result.

您可以选择行,然后删除返回的结果。

public void test() {
        List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
        DataSet ds = new DataSet();
        SqlDataAdapter da = null;
        DataTable dt = new DataTable();

        //Removes from DataTable 
        for (int x = 0; x < ListLinkedIds.Count(); x++)
        {
            DataRow[] matches = dt.Select("ID='" + ListLinkedIds[x] + "'");
            foreach (DataRow row in matches) {
                dt.Rows.Remove(row);
            }
        }


    }

回答by CodingSlayer

Try Deleteafter datatable is populated.

填充数据表后尝试删除

for (int x = 0; x < ListLinkedIds.Count(); x++)
{
   foreach (DataRow dr in dt.rows)
        {
           if(dr["id"] == ListLinkedIds[x])
             dr.Delete();
        }
        dt.AcceptChanges();
}