根据条件从数据表中删除行
本文关键字:删除行 数据表 条件 | 更新日期: 2023-09-27 18:24:50
我有一个列表,其中包含一些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();
我试过dt。Rows.RemoveAt(remove),但只删除行号。我想删除ListLinkedId中的每一行。
使用LINQ,您可以创建一个新的DataTable
,如:
DataTable newDataTable = dt.AsEnumerable()
.Where(r=> !ListLinkedIds.Contains(r.Field<string>("IDCOLUMN")))
.CopyToDataTable();
您可以选择行,然后删除返回的结果。
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);
}
}
}
填充数据表后尝试删除。
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
foreach (DataRow dr in dt.rows)
{
if(dr["id"] == ListLinkedIds[x])
dr.Delete();
}
dt.AcceptChanges();
}