Hi
I want to convert sql query to c# lambda query
SQL
selelct * from ABC where joiningdate between (Select top 1 DateAdd(d, -90,joiningdate) from ABC order by joiningdate desc) and (Select top 1 joiningdate from ABC order by joiningdate desc)I need to convert WHERE clause in c# lambda query
Thanks.


Tahir AnsariRank #366 · 6.8K reputationPosted Aug 12, 2023, 7:09 AM EDT
DateTime ninetyDaysAgo = DateTime.Now.AddDays(-90); var query = dbContext.ABC.OrderByDescending(x => x.JoiningDate); var result = dbContext.ABC.Where(item => item.JoiningDate >= query.Select(x => EntityFunctions.AddDays(x.JoiningDate, -90)).FirstOrDefault() && item.JoiningDate x.JoiningDate).FirstOrDefault() ).ToList();Mohammad HussainRank #513 · 4.8K reputationPosted Aug 12, 2023, 6:02 AM EDT
Here is how you can convert that SQL WHERE clause to C# lambda query:
var results = abc.Where(x => x.JoiningDate >= abc.OrderByDescending(y => y.JoiningDate).FirstOrDefault().JoiningDate.AddDays(-90) && x.JoiningDate y.JoiningDate).FirstOrDefault().JoiningDate);This filters for entities in abc whose JoiningDate is between the max date minus 90 days and the max date overall.
Amit MohantyRank #112 · 20K reputationPosted Aug 17, 2023, 1:48 AM EDT
var dbContext = new YourDbContext(); // Replace with your actual DbContext instance DateTime startDate = dbContext.ABC .OrderByDescending(item => item.JoiningDate) .Select(item => item.JoiningDate) .FirstOrDefault() .AddDays(-90); var result = dbContext.ABC .Where(item => item.JoiningDate >= startDate) .Where(item => item.JoiningDate item.JoiningDate)) .ToList();Cr BhargaviRank #420 · 5.9K reputationPosted Aug 13, 2023, 3:52 AM EDT
using System; using System.Linq; class Program { static void Main(string[] args) { // Your collection of ABC objects (assuming you have a class named ABC) IQueryable abcCollection = ...; // Subquery to get the date for lower range var lowerDate = abcCollection .OrderByDescending(item => item.JoiningDate) .Select(item => item.JoiningDate) .FirstOrDefault(); // Subquery to get the date for upper range var upperDate = abcCollection .OrderBy(item => item.JoiningDate) .Select(item => item.JoiningDate) .FirstOrDefault(); // Construct the lambda query var result = abcCollection .Where(item => item.JoiningDate >= lowerDate.AddDays(-90) && item.JoiningDate <= upperDate) .ToList(); // Execute the query // Now 'result' contains the filtered items based on the given condition } } class ABC { public DateTime JoiningDate { get; set; } // Other properties of ABC class }