在我的Datatable列中有一些特殊字符。所以想要删除有特殊字符的行。
我的数据表:
姓名联系人
Alex 9848598485
Paul @ 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);
我不删除特殊字符。 请帮助我
答案 0 :(得分:0)
以下是根据我的理解你可以做什么的一个例子......你的变量名和加载数据的过程会有所不同。您可以使用Regex和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();