How to filter by a part of the date dynamically

c# datetime dynamic-linq dynamic-linq-core linq

Question

If I want to build a specific rule in dynamic query where part of the condition states that

the same month of the year

I have the following datasource :

List<Excuse> li = new List<Excuse>();
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today, ExcuseDuration = new TimeSpan(0, 30, 0), ExcuseType = 0, Id = 1 });
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today.AddDays(1), ExcuseDuration = new TimeSpan(2, 30, 0), ExcuseType = 0, Id = 2 });
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today.AddDays(2), ExcuseDuration = new TimeSpan(2, 0, 0), ExcuseType = 0, Id = 3 });
li.Add(new Excuse { EmpNum = 2345, ExcuseDate = DateTime.Now, ExcuseDuration = new TimeSpan(0, 30, 0), ExcuseType = 0, Id = 4});

How to write something like that :

var langExp = "YEAR(ExcuseDate) = @1 AND MONTH(ExcuseDate) = @2 AND emp_num = @3";
var query1 = li.AsQueryable().Where(langExp, 2019,5,3333);

I want methods like Year() or Month() or the equivalent method to do something like that.

1
0
5/6/2019 3:12:24 PM

Accepted Answer

This should work easily with Dynamic LINQ:

var langExp = "ExcuseDate.Year = @0 && ExcuseDate.Month = @1 && EmpNum = @2";
var query1 = li.AsQueryable().Where(langExp, 2019, 5, 3333);
2
5/6/2019 7:59:44 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow