Remove rows from datatable based on a List using Linq

26 March 2022 | Viewed 8549 times

I have a DataTable with some data and a exclusion List<string> like below

ExamData (datatable)
ExamYear Completed
AZ-900: Azure Fundamentals2019
DP-900: Azure Data Fundamentals2021
AI-900: Azure AI Fundamentals2021
PL-900: Azure Power Platform Fundamentals2020

ExclusionYears (list)
[2018, 2019, 2020]

To remove rows from DataTable if "Year Completed" contains in exclusion list.

Here is the code (LINQ):

C# Code
List<DataRow> removeRows = ds.Tables[0].AsEnumerable()
.Where(r => list.Contains(r.Field<string>("Year Completed")))
.ToList();
removeRows.ForEach(ds.Tables[0].Rows.Remove);
ds.Tables[0].AcceptChanges();


Output
ExamYear Completed
DP-900: Azure Data Fundamentals2021
AI-900: Azure AI Fundamentals2021

PreviousNext