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();
Related
I'm trying to do a conditional OrderBy but it's having no effect. The List outputs the same with default ordering.
I've tried both approaches suggested in this question Conditional "orderby" sort order in LINQ
var query = _context.Groups
.Where(gr => gr.Status != ((sbyte)ActiveStatus.DELETED)
&& gr.OrganisationId == user.OrganisationId
&& (search != null && gr.Name != null ? (gr.Name.Contains(search)) : true == true)
)
.Select(GroupReportModel.Projection);
if(!pager.Sort.HasValue || pager.Sort.Value == ((int)Sort.MODIFIED))
query.OrderByDescending(gr => gr.Created.Date);
if(pager.Sort.Value == ((int)Sort.NAME))
query.OrderByDescending(gr => gr.Name);
pager.TotalRecords = query.Count();
var list = query.Skip(pager.PageCount != null ? pager.PageCount.Value * (pager.Page.Value) : 0)
.Take(pager.PageCount != null ? pager.PageCount.Value : 0)
.ToList();
LINQ methods do not mutate the query object, they return a new one, you need to reassign it:
if(!pager.Sort.HasValue || pager.Sort.Value == ((int)Sort.MODIFIED))
query = query.OrderByDescending(gr => gr.Created.Date);
if(pager.Sort.Value == ((int)Sort.NAME))
query = query.OrderByDescending(gr => gr.Name);
....
I want to do a query with lambda expression.
My database is a Cosmos DB.
I want to filter for two parameters and one of the two can be null.
For example i want to search for name and lastname and one of both is null.
This is that I am trying:
var result = this._client.CreateDocumentQuery<Person>(
UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions)
.Where((f) => f.Name == Name && f.LastName == lastName )
.AsEnumerable()
.ToList();
So this?
var result = this._client.CreateDocumentQuery<Person>(
UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions)
.Where((f) => (f.Name == Name || (f.Name == null && f.LastName != null)) && (f.LastName == lastName || (f.LastName == null && f.Name != null))
.AsEnumerable()
.ToList();
try something like this:
var result = this._client.CreateDocumentQuery<Person>(
UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions)
.Where(f => f.Name == $"{Name ?? f.Name}") &&
f.LastName == $"{lastName ?? f.LastName}") )
.AsEnumerable()
.ToList();
Maybe you can work with IQueryable:
IQueryable<Person> iPerson = this._client.CreateDocumentQuery<Person>(
UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions);
if(Name != null) iPerson = iPerson.Where(f => f.Name == Name);
if(lastName != null) iPerson = iPerson.Where(f => f.LastName == lastName)
return iPerson.AsEnumerable().ToList();
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();
I want to fetch the records as follows
SearchResult.condition is null then fetch all the rows from Person
if SearchResult.condition is false then fetch the rows where PersonType column contains null value
if SearchResult.condition is true then fetch the rows where PersonType column contains non null value
struct SearchResult
{
public string Name;
public bool? condition;
}
Expression<Func<Person, bool>> expression;
if(condition==null)
{
expression= (a =>
(SearchResult.Name==null || a.Name == SearchResult.Name)
);
}
else if(condition.Value == true)
{
expression= (a =>
(SearchResult.Name==null || a.Name == SearchResult.Name)
&& a.PersonType != null)
}
else if(condition.Value == false)
{
expression= (a =>
(SearchResult.Name==null || a.Name == SearchResult.Name)
&& a.PersonType == null)
}
I want to write the expression in one expression instead of using if else conditions. Can u plz help me in it?
Well you can do it with a conditional operator, but you need to specify the type of the expression tree for each lambda expression:
var expression = condition == null
? (Expression<Func<Person, bool>>) a => SearchResult.Name == null ||
a.Name == SearchResult.Name
: condition.Value
? (Expression<Func<Person, bool>>) a => (SearchResult.Name == null ||
a.Name == SearchResult.Name) &&
a.PersonType != null
: (Expression<Func<Person, bool>>) a => (SearchResult.Name == null ||
a.Name == SearchResult.Name) &&
a.PersonType == null;
But assuming you're going to use this with a LINQ query, you'd be much better off with something like:
var query = foo.Where(a => SearchResult.Name == null ||
a.Name == SearchResult.Name);
if (condition != null)
{
query = condition.Value ? query.Where(a => a.PersonType != null)
: query.Where(a => a.PersonType == null);
}
As an aside, I'd strongly advise you to avoid writing mutable structs or using public fields.
You could shorten as:
expression = a =>
(SearchResult.Name == null || a.Name == SearchResult.Name) &&
(SearchResult.condition == null || Search.condition == (a.PersonType != null));
Hi any suggestions on building a LINQ statement based on search criteria?
I'll be passing in an instance of a 'SearchCriteria' class with all parameters nullable.
I then want to
if (sc.a != null)
// add to where
if (sc.b != null)
// add to where
The key thing is these are to be ORs not ANDs.
Any tips?
And for bonus points I'd like to use 'contains' on an int? but I can only get equals or not equals.
Try:
.Where(x =>
(x.a != null ? x.a == a : false) &&
(x.b != null ? x.b == b : false));
or
.Where(x =>
(x.a != null && x.a == a) ||
(x.b != null && x.b == b));
Also:
.Where(x => new int[] { 1, 2, 3 }.Contains(x.i));