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
Remove Row from DataTable Depending on Condition
提问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 DataTable
like:
使用 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);
}
}
}