Only check date condition when DateTime?(nullable?) using LINQ - c#

I need check if any record exists on current date. But AddOn is nullable date. If I check below condition is throwing error because I am trying get date from null.
var cusRelationships = SvcClient.Client.Context.CusRelationships.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.Value.Date == DateTime.Now.Date).Select(c => c).ToList();
How compare date for current date?

Just check for null before the using the Value.
var cusRelationships = SvcClient.Client.Context.CusRelationships.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.HasValue &&
c.AddedOn.Value.Date == DateTime.Now.Date).Select(c => c).ToList();

var cusRelationships = SvcClient.Client.Context.CusRelationships
.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.HasValue &&
c.AddedOn.Value.ToShortDateString() == DateTime.Now.ToShortDateString())
.Select(c => c)
.ToList();

Related

How to use a conditional or in linq and C#

In the following GetByExpression, sometimes the r.branchid is null. How do I add a conditional in there so it utilises a different field (r.Invoice.Branch.Id) to check against when r.branchid is null?
var t = receiptRepo
.GetByExpression(r => r.BranchId == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();
Use a ternary operation
(r.BranchId != null? r.BranchId:r.Invoice.Branch.Id ) == branchId //or whatever you want to compare
You can try using null-coalescing operator ??:
r => (r.BranchId ?? r.Invoice.BranchId) == branchId
Here if r.BranchId is null we use r.Invoice.BranchId to compare with branchId. Note, that we can chain ?? operators, e.g.
r => (r.BranchId ?? r.Invoice.BranchId ?? r.Bill.BranchId) == branchId
we try BranchId if it's null, we have a look at r.Invoice.BranchId and if it's null we get r.Bill.BranchId etc.
Your Linq query can be
var t = receiptRepo
.GetByExpression(r => (r.BranchId ?? r.Invoice.BranchId) == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();
You can do this:
var t = receiptRepo
.GetByExpression(r => (r?.BranchId ?? r.Invoice.BranchId) == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();

Get Values from single column based on condition

I have query and I can display values based on condition in SQL. But how can write C# LINQ query is my question.
SELECT Value
FROM db.table
WHERE xxId = 1 AND YYid = 2 AND IsActive = '1' AND IsDeleted = '0'
Result
NNNN
MMMM
TTTT
VVVV
LLLL
I need same query in LINQ C#
var results = db.table
.Select(a => a.xxid == xxid && a.yyid == id &&
a.IsActive && !a.IsDeleted).value;
var results = db.table
.Where(a => a.xxid == xxid && a.yyid == id && a.IsActive && !a.IsDeleted)
.Select(a => a.value)
.ToList();

LINQ conditional query where value might be null

I'm trying to write a query to select data from database. I have the following code :
from notes in ctx.Notes
.Where(x => x.UserId== user.UserId
|| x.UserId == user.FamilyId
|| x.UserId == user.CompanyId).DefaultIfEmpty()
The problem with this is that the FamilyId and CompanyId are both nullable types and may not have any value at all which corrupts the whole query. How can I rewrite it so it only looks for FamilyId/CompanyId if they have values?
Create condition query:
var users = ctx.Notes.Where(x => x.UserId == user.UserId);
if (user.FamilyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.FamilyId));
}
if (user.CompanyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.CompanyId ));
}
var result = users.ToArray();
Simple, just add an AND clause to check if it's not null:
from notes in ctx.Notes.Where(x => x.UserId== user.UserId || (user.FamilyId ! =null && x.UserId == user.FamilyId) || (user.CompanyId !=null && x.UserId == user.CompanyId)).DefaultIfEmpty()

Linq - Dynamic Condition

I have the following query :-
I want to add one more condition which is dynamic, so if user passes DATEOFBIRTH it should be e.DateOfBirth <= date.
var data = ctx.Employee.Where(e => e.Id == Id
&& e.Category == Category
&& e.DateOfJoining <= date)
.Select(e => e)
.ToList();
How to condition dynamically?
You can use reflection to solve this problem but there is another idea that may helps you:
var criteria = new Dictionary<string, Func<Employee, bool>>();
var date = DateTime.Now; //or any other value
//Initialize your criterias
criteria.Add("DATEOFBIRTH", e => e.DateOfBirth <= date);
criteria.Add("DateOfJoining", e => e.DateOfJoining <= date);
var selectedValue = "DATEOFBIRTH";
var data = ctx.Employee.Where(e => e.Id == id &&
e.Category == Category &&
criteria[selectedValue](e)).ToList();
So if you change the selectedValue the output will be based on corresponding criteria you are looking for.
From your comment:
If the DateOfBirth is choosen, there where condition should be appended
by one more condition e.DateOfBirth <= date.. if user chooses
DateOfAnniversary then it should be e.DateOfAnniversary <= date
Then you could use:
var data = ctx.Employee
.Where(e => e.Id == Id && e.Category == Category && e.DateOfJoining <= date);
Now, assuming that filterbyDateOfBirth and filterbyDateOfAnniversary are bools:
if(filterbyDateOfBirth)
data = data.Where(e => e.DateOfBirth <= date);
if(filterbyDateOfAnniversary)
data = data.Where(e => e.DateOfAnniversary <= date);
var list = data.ToList();
Due to LINQ's deferred execution the database is queried just once at ToList.
Sounds like you're trying to do the following:
var employees = ctx.Employee.Where(e => e.Id == Id
&& e.Category == Category
&& e.DateOfJoining <= date);
if (!string.IsNullOrWhiteSpace(DATEOFBIRTH))
{
employees = employees.Where(e => e.DateOfBirth <= DATEOFBIRTH);
}
var data = employees.ToList();
You could also do the following, which is more concise, but since it looks like you are querying a database here, I would prefer the above approach since it doesn't include anything unnecessary in the query.
var data = ctx.Employee.Where(e => e.Id == Id &&
e.Category == Category &&
e.DateOfJoining <= date &&
(string.IsNullOrWhiteSpace(DATEOFBIRTH) ||
e.DateOfBirth <= DATEOFBIRTH))
.ToList();

how to show result using multiple Order by descending using linq query

I am having 3 criteria. I want to order these 3 types.
Who Paid with Master User
Who Update their Post Latest Date
Who Paid with Sub Master User
which one is having count it will come to top 15 Jobs.
My code here:
var orderMaster= _vasRepository.GetOrderDetails()
.Where(od => od.OrderMaster.OrganizationId != null &&
od.OrderId == od.OrderMaster.OrderId &&
od.OrderMaster.PaymentStatus == true &&
od.ValidityTill.Value >= currentdate)
.OrderByDescending(od => od.ValidityTill)
.Select(ord => ord.OrderMaster.Id.Value);
var updatedVacancyList = _repository.GetJobs()
.Where(c => c.UpdatedDate != null &&
updateFresh <= c.UpdatedDate)
.Select(c => c.Id);
var orderLatestUser = _vasRepository.GetOrderDetails()
.Where(od => od.OrderMaster.UserId != null &&
od.OrderMaster.PaymentStatus == true &&
freshUser <= od.ActivationDate &&
od.ValidityTill.Value >= currentdate)
.Select(c => c.OrderMaster.User.Id);
Then I check the count of those then assign to
List<int> lstMasterId = orderOrganization.ToList();
List<int>lstUpdatedJobsListId = updatedVacancyList.ToList();
List<int>lstUserListId= orderLatestUser.ToList();
Here i order the lists using query
Func<IQueryable<Job>, IOrderedQueryable<Job>> orderingFunc = query =>
{
if (orderMaster.Count() > 0)
return query.OrderByDescending(rslt =>
lstOrganizationId.Contains(rslt.OrganizationId))
.ThenByDescending(rslt=>lstUserListId.Contains(rslt.User.Id))
.ThenByDescending(rslt => lstUpdatedJobsListId.Contains(rslt.Id))
.ThenByDescending(rslt => rslt.CreatedDate);
else
return query.OrderByDescending(rslt => rslt.CreatedDate);
};
jobs = orderingFunc(jobs);
}
I want to show the lstUserListId at top of the result.. How to do this?

Categories

Resources