Question

I have a data table with a date column in it (RequestDate). I need to remove all rows where value in the RequestDate column is older than 30 days, using Linq.

Was it helpful?

Solution 2

You can use LINQ to find rows that should be deleted:

var rowsToDelete = source.AsEnumerable()
                         .Where(r => DateTime.Now - r.Field<DateTime>("RequestDate") > TimeSpan.FromDays(30))
                         .ToList();

But still need foreach loop to delete the rows from source DataTable:

foreach(var row in rowsToDelete)
    source.Remove(row);

OTHER TIPS

Try this:

dt.Rows.OfType<DataRow>()
    .Where(r => DateTime.Now.Date - r.Field<DateTime>("RequestDate").Date > TimeSpan.FromDays(30))
    .ToList()
    .ForEach(r => r.Delete());

Simple Solution here:

Dim rows As DataRow() = (From anyNamehere In yourTableName.AsEnumerable().Cast(Of DataRow)() Where anyNamehere .Field(Of Integer)("id") = 1).ToArray()
                    For Each row As DataRow In rows
                        yourTableName.Rows.Remove(row)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top