Reputation: 353
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;
}
Upvotes: 4
Views: 4670
Reputation: 3219
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
}
Upvotes: 0
Reputation: 460228
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));
Upvotes: 5
Reputation: 813
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
Upvotes: 2