user
user

Reputation: 833

Linq query with month difference between 2 dates

I have 2 Field FromDate and ToDate in database. I want the result LINQ query for records that have month difference of 2 dates with some dynamic value.

Actually I have one database table as EmploymentHistory with field NameOfCompany as nvarchar(50), ProfileID as bigint, EmoploymentFrom as datetime, EmploymentUpto as datetime, IsCurrentEmployer as bit.

ProfileID is reference key of Profile I want to generate a query for all profiles by experience in month.

if IsCurrentEmployer is true then EmploymentUpto is null.

Upvotes: 2

Views: 16611

Answers (4)

Jaime Yule
Jaime Yule

Reputation: 1081

Asuming you are using entity framework.. u may

Query(q => q.ToDate < DateTime.Today && q.FromDate > DateTime.Today.AddMonths(-2))

Query is any Iqueryable.. could be select, first, firstOrDefault.. of course you can change DateTime.Today to yours params.

Upvotes: 2

Oleks
Oleks

Reputation: 32333

If you're under .NET 4+ you could try EntityFunctions.DiffMonths utility method e.g.:

var query = query
            .Where(i=> 
                 EntityFunctions.DiffMonths(i.FromDate, i.ToDate) == 2
            );

Upvotes: 12

James
James

Reputation: 2463

Once you pull the dates out of the db, you can perform a zip operation with the subtract func as the selection argument.

IEnumerable<DateTime> datesA = //blah;
IEnumerable<DateTime> datesB = //blah;
IEnumerable<DateTime> differences = 
  datesA.Zip( datesB, (dA,dB) => dA.Subtract(dB));

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

you can execute this code

var resultWithMonth = datevalue2.Subtract(datevalue2).Days / (365.25 / 12)

Upvotes: 0

Related Questions