4

I have a DataTable and I want to remove all the rows matching a List< string>, how to do that? Following is my code,

public static DataTable GetSkills(List<Skill> EnteredSkills)
{
    DataTable dt = new DataTable();
    dt = GetDBMaster("SkillMaster");
    List<string> MatchingSkills = EnteredSkills.Select(c => c.Text).ToList();
    //Logic to Delete rows MatchingSkills from dt here
    return dt;
}

Final Solution

    public static DataTable GetSkills(List<Skill> EnteredSkills)
    {
        DataTable dt = new DataTable();
        dt = GetDBMaster("SkillMaster");
        var MatchingSkills = new HashSet<string>(EnteredSkills.Select(c => c.Text));
        List<DataRow> removeRows = dt.AsEnumerable().Where(r => MatchingSkills.Contains(r.Field<string>("DataTableSkillColumnName"))).ToList();
        removeRows.ForEach(dt.Rows.Remove);
        return dt;
    }
  • Can't you simply loop and check the matching rows and delete it from the data table ? – Devesh Mar 21 '18 at 11:46
  • Yes, but is there a better way to do this, there are many such situations in my entire project. – Prasanth Kumar Vinakota Mar 21 '18 at 11:47
  • What is happening inside the method `GetDBMaster()`, why don't you include the `MatchingSkills` as a condition in the query that populates the datatable? – sujith karivelil Mar 21 '18 at 11:51
  • GetDBMaster gives the skillmaster from a static datatble variable, which is loaded from DB only once when the first user makes a request to my page. So it has complete master, I am trying to filter rows from that master here. – Prasanth Kumar Vinakota Mar 21 '18 at 11:55

3 Answers3

5

Presuming the column is SkillName

List<DataRow> removeRows = dt.AsEnumerable()
    .Where(r => MatchingSkills.Contains(r.Field<string>("SkillName")))
    .ToList();
removeRows.ForEach(dt.Rows.Remove);

Side- note: i would use a HashSet<string> because it would be more efficient:

var MatchingSkills = new HashSet<string>(EnteredSkills.Select(c => c.Text));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

The simplest way will be:

var lstRemoveColumns = new List<string>() { "ColValue1", "ColVal2", "ColValue3", "ColValue4" };
List<DataRow> rowsToDelete = new List<DataRow>();

foreach (DataRow row in dt.Rows) 
{
    if (lstRemoveColumns.Contains(row["ColumnName"].ToString())) 
    {
        rowsToDelete.Add(row);
    }
}

foreach (DataRow row in rowsToDelete) 
{
    dt.Rows.Remove(row);
}

dt.AcceptChanges();

Look here

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Praneet Nadkar
  • 823
  • 7
  • 16
0

This solution works great! I'm using it for my solution.

List<DataRow> lsFilteredData = dtUnfilteredData.AsEnumerable().Where(q => lsWhatIWanted.Contains(q.Field<string>("Code"))).ToList();

foreach (DataRow drFilteredData in lsFilteredData)
{
    //Do whatever you want here
}
TPG
  • 2,811
  • 1
  • 31
  • 52