Linq search query using || - linq

I get this to work ok:
var results = db.GetProducts().Where(p => p.ProductName.Equals(searchQuery, StringComparison.OrdinalIgnoreCase));
When I use the || comparision to get my new query as:
var results = db.GetProducts().Where(p => p.ProductName.Equals(searchQuery, StringComparison.OrdinalIgnoreCase)) || db.GetProducts().Where(p => p.ProductId.ToString().Equals(searchQuery, StringComparison.OrdinalIgnoreCase));
I end up with:
Error 1 Operator '||' cannot be applied to operands of type
'System.Collections.Generic.IEnumerable<Uppgift_1.Models.MyProduct>' and
'System.Collections.Generic.IEnumerable<Uppgift_1.Models.MyProduct>' C:\Home\Programming
\cSharp\projects\MVC_projects\Uppgift_1\Uppgift_1\Controllers\ProductController.cs
23 27 Uppgift_1
How can I do if I want to include both statements in the search query ?

You need to put both conditions in the same Where.
var results = db.GetProducts()
.Where(p => p.ProductName
.Equals(searchQuery,
StringComparison.OrdinalIgnoreCase) ||
p.ProductId.ToString()
.Equals(searchQuery,
StringComparison.OrdinalIgnoreCase));

Try this:
var results = db.GetProducts()
.Where(p => p.ProductName.Equals(searchQuery, StringComparison.OrdinalIgnoreCase)
|| p.ProductId.ToString().Equals(searchQuery, StringComparison.OrdinalIgnoreCase));

Related

LINQ to SQL - WHERE clause filtered

Why is the where condition not applied in the following code? When I search, the results are not getting filtered. When I debug, searchString does have a value and execution is going through the _data.Where clause but it's not returning the filtered result.
What I'm doing wrong here?
IQueryable<UserViewModel> _data = (
from a in context.aspnet_Users
join b in context.aspnet_Membership on a.UserId equals b.UserId
where b.IsApproved == true
select new UserViewModel
{
UserId = a.UserId,
UserName = a.UserName,
FirstName = a.FirstName,
LastName = a.LastName,
EmailAddress = b.Email
})
.OrderBy(a => a.FirstName)
.ThenBy(b => b.LastName);
if (!String.IsNullOrEmpty(searchString))
{
_data = _data
.Where(x => x.FirstName.Contains(searchString))
.Where(y => y.UserName.Contains(searchString))
.Where(y => y.LastName.Contains(searchString))
.Where(y => y.EmailAddress.Contains(searchString));
}
The way the second query is written checks for records where all filtered fields start with the search string, ie for users whose FirstName and LastName and UserName and Email all start with the same string.
I think what you wanted was a query that check whether any of these fields starts with the search string, eg:
_data = _data.Where(x => x.FirstName.Contains(searchString) ||
x.UserName.Contains(searchString) ||
x.LastName.Contains(searchString) ||
x.EmailAddress.Contains(searchString));
I suspect this is doing a lot more "filtering" than you expect:
_data = _data.Where(x => x.FirstName.Contains(searchString))
.Where(y => y.UserName.Contains(searchString))
.Where(y => y.LastName.Contains(searchString))
.Where(y => y.EmailAddress.Contains(searchString));
This requires that searchString exist in all four of those fields. So if you search for, say, "David" then it's going to fail to find my record because my LastName doesn't contain that string.
Perhaps you wanted to use a logical or instead of a logical and? Something like this:
_data = _data.Where(x => x.FirstName.Contains(searchString) ||
x.UserName.Contains(searchString) ||
x.LastName.Contains(searchString) ||
x.EmailAddress.Contains(searchString));

Hide Join if string.IsNullOrEmpty using Linq

I got this linq query which searches for selected values in my database using dropdowns.
Is there a way to hide the "join" in the linq query if the ddlCategory is null? I want this because the result of the search shows duplicated-rows because my documents can have many Categories.?? hope you understand what i mean.. Can anyone help??
var documents = from d in data.tblDocuments
join sc in data.tblSubCategories on d.DocId equals sc.DocId
orderby d.Docyear descending
where
(string.IsNullOrEmpty(person) || d.DocPerson.Equals(person)) &&
(string.IsNullOrEmpty(year) || d.Docyear.Equals(year)) &&
(string.IsNullOrEmpty(law) || d.DocLaw.Equals(law)) &&
(string.IsNullOrEmpty(court) || d.DocCourt.Equals(court)) &&
(string.IsNullOrEmpty(category) || sc.CategoryId.Equals(category)) &&
(string.IsNullOrEmpty(casenr) || d.DocNr.Equals(casenr))
select d;
Use lambda syntax:
var query = data.tblDocuments;
if (condition) // conditionally add join
query = query.Join(data.tblSubCategories.Where(sc => sc.CategoryId == category),
d => d.DocId, sc => sc.DocId, (d,sc) => d);
// continue to compose query
query = query.OrderByDescending(d => d.Docyear)
.Where(d => ...);
BTW you can compose filtering based on conditions:
if (!String.IsNullOrEmpty(person))
query = query.Where(d => d.DocPerson == person);

Dynamic where condition in linq query expression

My Code :
IEnumerable<DataRow> whrRowEnum;
whrRowEnum = from r in dtInput.AsEnumerable()
where r.Field<string>("EMP_DEP") == "DEP1"
orderby EMP_DEP
select r;
The above code is working fine due to hard coded where condition, but In run-time I need to add multiple where condition in my linq query like r.Field("EMP_DEP") == "DEP1" && r.Field("EMP_ID") == "EMP1"
You can use lambda syntax to compose your query based on conditions:
IEnumerable<DataRow> query = dtInput.AsEnumerable();
if (condition1)
query = query.Where(r => r.Field<string>("EMP_DEP") == "DEP1");
if (condition2)
query = query.Where(r => r.Field<string>("EMP_ID") == "EMP1");
var whrRowEnum = query.OrderBy(r => r.Field<string>("EMP_DEP"));
Another option is adding conditions to query filter
whrRowEnum = from r in dtInput.AsEnumerable()
where (!condition1 || (r.Field<string>("EMP_DEP") == "DEP1")) &&
(!condition2 || (r.Field<string>("EMP_ID") == "EMP1"))
orderby EMP_DEP
select r;

Cannot implicitly convert type 'DateTime' to 'bool' linq query

I have this LINQ query:
var resourcePlanningInWeek = resourcePlanning.Where(rp => rp.PlanDate >= dateFrom && rp.PlanDate <= dateTo);
var holidays = new HolidayManager().GetByPeriod(dateFrom, dateTo);
var resourcePlanningExcludedHolidays= resourcePlanningInWeek.Where(rpiw => ( holidays.Where(h => h.HolidayDate = rpiw.PlanDate).Count = 0))
When executed, I get following error:
Cannot implicitly convert type 'DateTime' to 'bool'
Somewone know why?
You need to use == instead of = when you want to make a comparison. That's relevant at two places in the last line.
The call to Count is missing the parentheses.
var resourcePlanningExcludedHolidays = resourcePlanningInWeek
.Where(rpiw => holidays.Where(h => h.HolidayDate == rpiw.PlanDate)
.Count() == 0);
However, there is a better way of writing this:
var resourcePlanningExcludedHolidays = resourcePlanningInWeek
.Where(rpiw => !holidays.Any(h => h.HolidayDate == rpiw.PlanDate));
This is better, because:
It is shorter and more readable
It stops enumerating holidays as soon as the condition is true the first time. Count() always enumerates the complete list.
An even better approach would be to use a HashSet<DateTime>:
var holidays
= new HashSet<DateTime>(new HolidayManager().GetByPeriod(dateFrom, dateTo)
.Select(x => x.HolidayDate));
var resourcePlanningExcludedHolidays
= resourcePlanningInWeek.Where(rpiw => !holidays.Contains(rpiw.PlanDate));
You are missing an equal symbol at:
h.HolidayDate = rpiw.PlanDate
It should be:
var resourcePlanningExcludedHolidays=
resourcePlanningInWeek.Where(rpiw => ( holidays.Where(h => h.HolidayDate == rpiw.PlanDate).Count = 0))

Why am I geting this error: Operator ā€˜&&ā€™ cannot be applied to operands of type System.Linq.IQueryable?

Iā€™m trying to retrieve data from an entity and populate a viewModel property like this:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday") && (db.Enrollments.Where(b => b.CourseID == courseID);
but I get a operator && cannot be applied to operands of type System.Linq.IQerable<> error. Can you help with a way to find all Monday class with the same ID?
I tried this: viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday") but I get all Mondays courses but I want to limit them to a specific courseID.
Please help!
You need to examine your parentheses. This code won't even compile:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday")
&& (db.Enrollments.Where(b => b.CourseID == courseID);
In that code you're trying to use && between two calls to .Where(), which return an IQueryable. You probably mean to use && within the .Where() clause:
viewModel.Enrollments = db.Enrollments.Where(b => (b.classDays == "Monday")
&& (b.CourseID == courseID));
Or perhaps append a second .Where() clause:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday")
.Where(b => b.CourseID == courseID);
Note that .Where() can be chained indefinitely, essentially resulting in applying each clause in turn in an AND fashion in the resulting query.
&& Operator should be used with conditions inside where NOT with sets of enrollments (in your case)
Try This:
viewModel.Enrollments = db.Enrollments.Where(b => (b.classDays == "Monday") && (b.CourseID == courseID));

Resources