Linq opening and closing parentheses does not match - c#

I have this code:
using (Entities db = new Entities())
{
refer = db.Refferals.Where(r =>
r.RefferalDetails.Any(rd =>
(Name.Contains(rd.Name) || rd.Name.Contains(Name) || LastName.Contains(rd.LastName) || rd.LastName.Contains(LastName)
|| Company.Contains(r.Company) || r.Company.Contains(Company)
Mobile.Contains(rd.Mobile) || rd.Mobile.Contains(Mobile))) &&
Mobile.Length > 9 && Name.Length > 1 && LastName.Length > 1 && Company.Length > 2
).ToArray();
}
Although the parentheses count is correct but the editor offers that there is one extra parantheses.
I tried restarting Visual Studio but its the same.

Try adding the missing || between r.Company.Contains(Company) and Mobile.Contains(rd.Mobile).
And fix the indenting, that makes it much easier to see what's wrong. When I indented it, the missing operator stuck out like a sore thumb, and it's easy to see how the parens work.
using (Entities db = new Entities())
{
refer = db.Refferals.Where(r =>
r.RefferalDetails.Any(rd =>
(
Name.Contains(rd.Name)
|| rd.Name.Contains(Name)
|| LastName.Contains(rd.LastName)
|| rd.LastName.Contains(LastName)
|| Company.Contains(r.Company)
|| r.Company.Contains(Company)
|| /* <-- ADDED OR OPERATOR HERE */
Mobile.Contains(rd.Mobile)
|| rd.Mobile.Contains(Mobile)
)
)
&& Mobile.Length > 9
&& Name.Length > 1
&& LastName.Length > 1
&& Company.Length > 2
).ToArray();
}

It's missing one**||** before Mobile.Contains(rd.Mobile)
refer = db.Refferals.Where
(
r => r.RefferalDetails.Any
(
rd =>
(
Name.Contains(rd.Name) || rd.Name.Contains(Name) || LastName.Contains(rd.LastName) || rd.LastName.Contains(LastName)
|| Company.Contains(r.Company) || r.Company.Contains(Company)
|| Mobile.Contains(rd.Mobile) || rd.Mobile.Contains(Mobile)
)
)
&& Mobile.Length > 9 && Name.Length > 1 && LastName.Length > 1 && Company.Length > 2
).ToArray();

Without running code it seems you do some kind of unary selections (rd). I would suggest you start refactoring your code and break out each condition a part...

Related

Multiple Checkbox create LINQ

I have 4 checkboxes and based on which ones the user clicks on, I need to produce the LINQ statement. As mentioned below in the comment section, if I select just one checkbox, it works fine. If I select multiple checkboxes, it returns 0 results.
The 4 checkboxes are 1) "Item1" 2) "Item2" 3) "Item3" 4) "Item4".
This is what I have far:
var entity = _w_ItemRepository.GetMany(p => p.ID == id);
/* If I select just one item it works fine. If I select multiple items get 0 result */
entity = entity.Where
(p => (p.ItemType == 1 || !item1)
&& (p.ItemType == 2 || !item2)
&& (p.ItemType == 2 || !item3)
&& (p.ItemType == 3 || !item4)
);
I suspect the &&s need to be ||s. Consider if both item1 and item2 are true then you're essentially saying:
.Where(p => p.ItemType == 1 && p.ItemType == 2)
When the intent is probably:
.Where(p => p.ItemType == 1 || p.ItemType == 2)
(It also looks like there's a typo, you specify ItemType == 2 twice.)
Try:
entity = entity.Where
(p => (p.ItemType == 1 || !item1)
|| (p.ItemType == 2 || !item2)
|| (p.ItemType == 3 || !item3)
|| (p.ItemType == 4 || !item4)
);
Or I think this may be more clear, adding each clause if itemX is true:
entity = entity.Where
(p => (item1 && p.ItemType == 1)
|| (item2 && p.ItemType == 2)
|| (item3 && p.ItemType == 3)
|| (item4 && p.ItemType == 4)
);

limiting by an additional LINQ parameter

I have the following in an MVC application:
var selectedArticles =
vm.Articles.Except(
vm.Articles.Where(x => x.Quantity == 0)).ToList();
I need to add another parameter. I DONT want to show the articles where the option HideUntilDate != NULL && HideUntilDate > todays date
Any tips?
Except not needed
var selectedArticles = vm.Articles
.Where(a => a.Quantity == 0 && !(a.HideUntilDate != null && a.HideUntilDate.Value > DateTime.Today));
Just add the requirement logic to your where clause's lambda expression
var selectedArticles =
vm.Articles.Except(
vm.Articles.Where(
x => x.Quantity == 0 ||
x.HideUntilDate == null ||
x.HideUntilDate < DateTime.Now.Date()
)
).ToList();

Better way to write if-else block [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have following code (Sample code) which works very well.
I just think if there is any other better way we can write following code snippet more accurately with less code.
if(language == "English")
{
if(Student_id == 0)
{
someFunction();
}
else
{
if(getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)
{
someFunction();
}
}
}
Also, please note if Student_id is 0, getMarks(Student_id) throws error
(For more a complex scenario, check out this)
What I suggest for your case is:
To write it with less nested if-else block
one way to do it is by inverting the conditions and
gives early return whenever possible
To combine conditions with the same actions (in your case being the someFunction)
To exploit the Short Circuit Evaluation which is implemented in C# (also implemented in many other programming languages - as noted by Martheen in his comment).
if(language != "English")
return; //assuming nothing below
if(Student_id == 0 || getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)
someFunction(); //if someFunction is identical, this can be done
If you have other languages to be checked or if you have something to be done independent from your actions based on language == "English", however, then you should not return in the if (language != "English") statement:
if(language == "English") {
if(Student_id == 0 || getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)
someFunction(); //if someFunction is identical, this can be done
}
//Something else which must be done
Edit (after the question is edited):
For the additional condition, you can simply put it right after the Student_id == 0 because C# will always evaluate the left most if condition first (for its || short circuit evaluation).
To illustrate: for your case, this is ok:
if(Student_id == 0 || getMarks(Student_id) > 50){
//if Student_id == 0 is true, then getMarks(Student_id) wouldn't get evaluated
}
But this is not ok:
if(getMarks(Student_id) > 50 || Student_id == 0){
//if Student_id is 0, then getMarks(Student_id) would throw exception before Student_id == 0 is evaluated
}
In terms of readability, it sometimes helps to give your conditions readable names:
var languageIsEnglish = language == "English";
var studentIdIsNotSet = Student_id == 0;
var hasMoreThanOneSubject = subjectCount > 1;
var hasProjects = projectCount > 0;
if(languageIsEnglish && (studentIdIsNotSet || (hasMoreThanOneSubject || hasProjects )))
{
someFunction();
}
This might work;
if(language == "English" && (Student_id == 0 || getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0))
{
someFunction();
}
if(language == "English")
{
if(Student_id == 0 || getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)
{
someFunction();
}
}
Your else block doesn't offer any alternative and in fact calls the same function. In that case there is no need for another if block.
If there is no else for the 1st if I think you can write it in one line like this
if(language == "English" && (Student_id == 0 || (getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)))
someFunction();
if there is an else you can do it like this
if(language == "English")
{
if(Student_id == 0 || getMarks(Student_id) > 50 || subjectCount > 1 || projectCount > 0)
someFunction();
}
else
{
}

Why is my query not returning anything

I was writing a LINQ query to filter the records based on user input and selection. Some of the inputs may not be given from the user. So i need to filter based on the given input. I tried giving value for only 1 out of 5 optional inputs. But the query is not returning anything. Please help me to find the proper query. you can better understand after seeing the query.
Code
var model = (from items in Db.Items
where ((items.ItemNo == null ||
items.ItemNo == String.Empty) ||
((items.ItemNo.CompareTo(DD.FromItemNo) >= 0) &&
(items.ItemNo.CompareTo(DD.ToItemNo) <= 0))) &&
(items.InfoTypeId == 0 ||
(items.InfoTypeId == DD.InfoType)) &&
(items.CreatedOn == null ||
(items.CreatedOn >= DD.Start &&
items.CreatedOn <= DD.End)) &&
(items.StatusId == 0 ||
(items.StatusId == DD.Status)) &&
(items.LocationId == 0 ||
(items.LocationId == DD.Location)) &&
(items.CollectionId == 0 ||
(items.CollectionId == DD.Collection))
select new ViewModel()
{
Itemid = items.Id,
INo = items.ItemNo,
BTags = (from asd in Db.BibContents
where asd.BibId == items.BibId &&
asd.TagNo == "245" &&
asd.Sfld == "a"
select asd.Value).FirstOrDefault(),
Sid = (from stat in Db.ItemStatus1
where stat.Id == items.StatusId
select stat.Description).FirstOrDefault(),
Option = DD.Option,
CurrItemNo = DD.ItemNumber
}).ToList();
You've got to check the values of DD for nulls or 0s, not those of items:
var model = (from items in Db.Items
where
(
(DD.ItemNo == null || DD.ItemNo == String.Empty)
|| (items.ItemNo.CompareTo(DD.FromItemNo) >= 0 && items.ItemNo.CompareTo(DD.ToItemNo) <= 0)
)
&& (DD.InfoTypeId == 0 || (items.InfoTypeId == DD.InfoType))
&& (DD.CreatedOn == null || (items.CreatedOn >= DD.Start && items.CreatedOn <= DD.End))
&& (DD.StatusId == 0 || (items.StatusId == DD.Status))
&& (DD.LocationId == 0 || (items.LocationId == DD.Location))
&& (DD.CollectionId == 0 || (items.CollectionId == DD.Collection))
select ...

Entity framework strings using greater than operator

How do I make this query work like it does in sql? In sql I can use < and > operators on strings.
I've been googling this for about 20 minutes and have found no solution yet.
I cannot convert r.ExemptionCode to an integer as it may have values like '91A,9AA,ZZZ,Z01'
from r in results
where (r.ExemptionCode > "900" || r.ExemptionCode == "701" || r.ExemptionCode == "702" || r.ExemptionCode == "721" || r.ExemptionCode == "724")
select r
Try this :
from r in results
where (r.ExemptionCode.CompareTo("900") > 0 || r.ExemptionCode == "701" || r.ExemptionCode == "702" || r.ExemptionCode == "721" || r.ExemptionCode == "724")
select r

Categories

Resources