Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete row from datatable where first column does not contain (some string)

Tags:

c#

datatable

I have DataTable with the following columns:

ClientID date numberOfTransactions price

ClientID is of type string and I need to ensure that its contents include "A-" and "N6" for every value in the table.

I need to delete all rows from the DataTable where this first column (ClientID) does not contain both "A-" and "N6" (some totals and other unnecessary data). How can I select and delete these rows specifically from the DataTable?

I know this:

foreach (DataRow row in table.Rows) // Loop over the rows.
    {

        //Here should come part "if first column contains mentioned values
    }

I also know this

If (string.Contains("A-") == true &&  string.Contains("N6") == true)

{
//Do something
}

I need help how to implement this for first column of each row.

like image 693
el jefe Avatar asked Jan 25 '12 13:01

el jefe


3 Answers

Try this:

EDIT: Totally messed up that last line, so if you tried it, try it now that I made it not stupid. =)

List<int> IndicesToRemove = new List<int>();
DataTable table = new DataTable(); //Obviously, your table will already exist at this point
foreach (DataRow row in table.Rows)
{
   if (!(row["ClientID"].ToString().Contains("A-") && row["ClientID"].ToString().Contains("N6")))
      IndicesToRemove.Add(table.Rows.IndexOf(row));
}
IndicesToRemove.Sort();
for (int i = IndicesToRemove.Count - 1; i >= 0; i--) table.Rows.RemoveAt(IndicesToRemove[i]);
like image 165
Chris Barlow Avatar answered Oct 07 '22 16:10

Chris Barlow


try using this,

assuming dt as your Datatabe object and ClientID as your first column (hence using ItemArray[0])

for(int i=0; i<dt.Rows.Count; i++)
{
  temp = dt.Rows[i].ItemArray[0].ToString();

if (System.Text.RegularExpressions.Regex.IsMatch(temp, "A-", System.Text.RegularExpressions.RegexOptions.IgnoreCase) || System.Text.RegularExpressions.Regex.IsMatch(temp, "N6", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
   {
     dt.Rows.RemoveAt(i);
     i--;
   }
 }

Simple and straight forward solution... hope it helps

like image 40
Bravo Avatar answered Oct 07 '22 17:10

Bravo


this should be more efficient, both in lines of Code and Time, try this :)

for(int x=0; x<table.Rows.Count;)
{
   if (!table.Rows[x].ItemArray[0].contains("A-") && !table.Rows[x].ItemArray[0].contains("N6"))
      table.Rows.RemoveAt(x);
   else x++;
}

Happy Coding

like image 33
Mabdullah Avatar answered Oct 07 '22 16:10

Mabdullah