Include in where statment only if not null - c#

I have the following :
how can i include a filter in my where statement only if it's not null?
i tried the following but i always get 0 records
public async Task<IList<UserRefDto>> GetUserRef(Dictionary<string, string> filter) {
var iod = 549; // a test user who has 2548 records in db
var favorites = filter.ContainsKey("fav") ? filter["fav"].ConvertToGuid(",") : null;
var histories = filter.ContainsKey("his") ? filter["his"].ConvertToGuid(",") : null;
var orders = filter.ContainsKey("ord") ? filter["ord"].ConvertToGuid(",") : null;
var result = await context.UserRefernces
.Where(x =>
x.User_iod = iod
&& (favorites != null && favorites.Contains((Guid)x.FavId))
&& (histories != null && histories.Contains((Guid)x.HistoryId))
&& (orders != null && orders.Contains((Guid)x.OrderId))
)
.AsNoTracking()
.ToListAsync()
.ConfigureAwait(false);
return result;
}
EDIT
Note: If all keys have values then i got records back, only if one or more is null i got nothing back from db

You can build your query with several .Where() statements, which will be added via an AND condition. But add the additional .Where() statements only when the values are present.
var query = context.UserRefernces
.Where(x => x.User_iod == iod);
if (favorites != null) {
query = query.Where(x => favorites.Contains((Guid)x.FavId));
}
// same for "histories" and "orders"
var result = await query
.AsNoTracking()
.ToListAsync()
.ConfigureAwait(false);

Replace favorites != null && with favorites == null || in your query as follows:
var result = await context.UserRefernces
.Where(x => x.User_iod = iod
&& (favorites == null || favorites.Contains((Guid)x.FavId))
&& (histories == null || histories.Contains((Guid)x.HistoryId))
&& (orders == null || orders.Contains((Guid)x.OrderId)))
.AsNoTracking()
.ToListAsync()
.ConfigureAwait(false);
return result;
Now the query will work as expected.

Related

LINQ Conditional OrderBy

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);
....

LINQ with Contains return zero rows if i am passing empty string

i don't know how to handle this in LINQ
simply i have a searchKey in which i am passing user enter data and it return with rows. but if i am not passing any searchkey it not given any data. i dont want to add contains if searchkey is empty :(
var AppointmentList = (from app in Con.ios_Appointment
where (app.IS_DELETED == false && app.CLINICIANID == appReq.id
&& app.FNAME.Contains(appReq.searchKey.Trim()) || app.LNAME.Contains(appReq.searchKey.Trim()) || app.ADDRESS.Contains(appReq.searchKey.Trim())
)
orderby app.DATE descending
select new
{
app.ID,
app.FNAME,
app.LNAME,
app.DATE,
app.LONGITUDE,
app.LATITUDE,
app.ADDRESS,
app.STATUS,
app.START_TIME
}).Skip(skipRecord).Take(Convert.ToInt32(record)).ToList();
I suggest you use method syntax to easily build the query up programatically:
var query = Con.ios_Appointment.Where(app => !app.IS_DELETED && app.CLINICIANID == appReq.id);
var search = appReq.searchKey.Trim();
if (search != "")
{
query = query.Where(app => app.FNAME.Contains(search) ||
app.LNAME.Contains(search) ||
app.ADDRESS.Contains(search));
}
var appointments = query
.OrderByDescending(app => app.DATE)
.Select(app => new
{
app.ID,
app.FNAME,
app.LNAME,
app.DATE,
app.LONGITUDE,
app.LATITUDE,
app.ADDRESS,
app.STATUS,
app.START_TIME
})
.Skip(skipRecord)
.Take(Convert.ToInt32(record))
.ToList();
You need to use string.IsNullOrWhiteSpace method:
where (app.IS_DELETED == false &&
app.CLINICIANID == appReq.id &&
(string.IsNullOrWhiteSpace(appReq.searchKey) ||
app.FNAME.Contains(appReq.searchKey.is Trim()) || ...

query with lambda expressions and one parameter is null

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();

Excluding Condition if Parameter is null

I am fetching data using LINQ and Lambda with 2 conditions using this Query. Is it possible to write this logic without if else condition -
public List<Pallet> GetPallet(string palletID, string locationID)
{
List<Pallet> data = new List<Pallet>();
if (locationID != null)
data = data.Where(x => x.PalletID == palletID && x.LocationID == locationID).ToList();
else
data = data.Where(x => x.PalletID == palletID).ToList();
return data;
}
Sure it is:
public List<Pallet> GetPallet(string palletID, string locationID)
{
List<Pallet> data = new List<Pallet>();
data = data.Where(x => x.PalletID == palletID && (locationID == null || x.LocationID == locationID)).ToList();
return data;
}
This is a way of doing it with correct results:
data = data
.Where(x => x.PalletID == palletID)
.Where(!string.IsNullOrEmpty(locationID)? x.LocationID == locationID : true)
.ToList();
NOTE: The accepted answer will return the wrong result although the syntax is correct. It'll always compares the LocationID even if the locationID is null or empty. Note that, in case of locationID == null we do not want to compare at all (we don't want this: x => x.LocationID == null).

LINQ using Contains with entity

Am using ASP.NET MVC 5 to create an Application for billing, now i have thing function which receive a filter object with different variables, am having a problem with contains when i search, what am i doing wrong
public static List<Quote> getCustomerQuotes(QuoteFilter filter)
{
using (var db = new AppDBContext())
{
var q = db.Quotes.Where(u => u.entryDate > 0); ;
if (filter.type != null)
{
q = q.Where(u => u.quoteType == filter.type);
}
if (filter.only_permitable != null)
{
q = q.Where(u => !Values.NON_PERMITABLE_QUOTES.Contains(u.quoteType));
}
if (filter.quote_status != null)
q = q.Where(u => u.quote_status == (int)filter.quote_status);
if (filter.quotenumber != null)
{
q = q.Where(u => u.quote_number.Contains(filter.quotenumber));
}
if (filter.permitnumber != null)
q = q.Where(u => u.permit_number.Contains(filter.permitnumber));
if (filter.permit_status != null)
q = q.Where(u => u.permit_status == (int)filter.permit_status);
if (filter.quoteId != null)
q = q.Where(u => u.Id == (int)filter.quoteId);
if (filter.customer_id != null)
q = q.Where(u => u.customer_id == (int)filter.customer_id);
q = q.OrderByDescending(u => u.Id);
FileLogger.Log("getCustomerQuotes", q.ToString());
return q.ToList();
}
}
When i call the function and pass quotenumber, the contains doesnt search, it returns nothing
You have to evaluate your expression, before you apply the OrderByDescending.
q = q.Where(u => u.quote_number.Contains(filter.quotenumber)).ToList();
This should be happen also to the rest places.
Is quote number alpha-numeric? If yes, as Contains is case sensitive can you try comparison by first turning source and target to same case ? like
q = q.Where(u => u.quote_number.ToLower().Contains(filter.quotenumber.ToLower()));
Cheers
Ok, am answering my own question after finding a solution or i may call it a hack
public static List<Quote> getCustomerQuotes(QuoteFilter filter)
{
using (var db = new AppDBContext())
{
var q = db.Quotes.Where(u =>
(filter.type != null ? u.quoteType == filter.type : u.quoteType > 0) &&
(filter.only_permitable != null ? !Values.NON_PERMITABLE_QUOTES.Contains(u.quoteType) : u.permitType > 0) &&
(filter.quote_status != null ? u.quote_status == filter.quote_status : u.quote_status > -100) &&
(!string.IsNullOrEmpty(filter.quotenumber) ? u.quote_number.Contains(filter.quotenumber) || u.groupName.Contains(filter.quotenumber) : u.quoteType > 0) &&
(!string.IsNullOrEmpty(filter.permitnumber) ? u.permit_number.Contains(filter.permitnumber) || u.groupName.Contains(filter.permitnumber) : u.quoteType > 0) &&
(filter.permit_status != null ? u.permit_status == filter.permit_status : u.quoteType > 0) &&
(filter.quoteId != null ? u.Id == filter.quoteId : u.Id > 0) &&
(filter.customer_id != null ? u.customer_id == filter.customer_id : u.customer_id > -1)
).OrderByDescending(u => u.Id);
//FileLogger.Log("getCustomerQuotes", q.ToString());
return q.ToList();
}
}
i dont know why it didn't work the first time but now it works.

Categories

Resources