如果数据表中有任何特殊字符,如何删除行
本文关键字:删除行 特殊字符 任何 数据表 如果 | 更新日期: 2023-09-27 18:35:49
在我的数据表中,列有一些特殊 characters.so 想要删除具有特殊字符的行。
我的数据表:
姓名联系人
亚历克斯·9848598485
保罗@9955221100
麦克风 #9988552211
我想删除第二行和第三行,因为它有特殊字符.我采取特殊的字符,例如
string [] chars=new string[] { ",", ".", "/", "!", "@", "#", "$",
"%", "^", "&", "*", "'", "'"", ";","_", "(", ")", ":", "|", "[", "]" };
public void deletespecialchars(DataTable dt, string[] ch)
{
ArrayList al = new ArrayList();
foreach (DataColumn row in dt.Columns)
{
if(al.Contains(ch))
al.Add(row);
if (al.Count > 0)
{
foreach (DataColumn dcol1 in al)
{
dt.Columns.Remove(dcol1);
}
}
}
}
当我调用此方法时,例如
deletespecialchars(dt,chars);
我不删除特殊字符。请帮助我
根据我的理解,这是您可以做什么的示例......变量名称和加载数据的过程将不同。你也许能够使用正则表达式和 Linq 用更少的代码获得相同的结果。
//array of bad chars you don't want in your data - Must be of char type
char [] chars=new char[] { '$','-','#'}; //Add all bad chars here...
//define and load the datatable
DataTable dt = new DataTable("test");
DataColumn c0 = new DataColumn("Contacts");
dt.Columns.Add(c0);
DataColumn c1 = new DataColumn("Serial");
dt.Columns.Add("c1");
DataColumn c3 = new DataColumn("Notes");
dt.Columns.Add(c3);
//load some data
dt.Rows.Add(new object[] {"a","1234$542341","no$$tes1"} );
dt.Rows.Add(new object[] {"b#","12342241","notes2"} );
dt.Rows.Add(new object[] { "c?", "-421341", "notes3" });
dt.Rows.Add(new object[] { "DD", "12345", "notes3" });
//loop through each cell, when a cell contains bad data,
//remove the entire row and skip remainig cells
if (dt == null) return;
Console.WriteLine("Rows before:" + dt.Rows.Count.ToString());
if (dt.Rows.Count == 0) return;
int c = dt.Rows.Count;
for (int r = c-1; r > -1; r--)
{
Console.WriteLine("***Row: ");
foreach (var item in dt.Rows[r].ItemArray) // Loop over the items.
{
if (item.ToString().IndexOfAny(chars) > -1)
{
Console.Write("Bad Content: ");
Console.WriteLine(item);
dt.Rows[r].Delete(); //remove row
break;//skip remaining cells
}
}
}
dt.AcceptChanges();
Console.WriteLine("Rows after:"+dt.Rows.Count.ToString());
Console.Read();