Checking for AND OR condition between two checks - c#

Hi I have following linq statement
var list=(from c in db.sales
where c.id ==id && || c.name==name
select new model
{
//.....
});
I am having problem with my where clause.
Basically I can get id and name values or either one of them can be null. So I am trying to use where clause with AND OR meaning both condition could be right or either one.
With this where syntax i get intelliscence error. Please let me know how I can use AND OR check in the where clause.

both condition could be right or either one
You simply need or and do not need and
var list=(from c in db.sales
where c.id ==id || c.name==name
select new model
{
//.....
});
The || (or Operator)
The conditional-OR operator (||) performs a logical-OR of its bool
operands. If the first operand evaluates to true, the second operand
isn't evaluated. If the first operand evaluates to false, the second
operator determines whether the OR expression as a whole evaluates to
true or false, MSDN.

It sounds like what you want is just an ordinary OR:
where c.id == id || c.name == name
This will evaluate to true if c.id == id is true, if c.name == name is true, or if both are true.

I think you mean IntelliSense error. This is obvious, because && || is not valid C# syntax.
From what you describe, I think you only need the OR operation.
Try changing && || to just ||.

Related

Any alternative for this 'Where' LINQ query

i have this linq query. I need to look for any good alternative if possible for this higlighted lambda expression inside Where condition. I was thinking to use coalesce condition ( ?? ) but couldnt make a query.
.Where(p => p.Property== null ? true : p.Property.SubPropertyList.Contains(Item))
So, I want to get those items from list which has a property null or if not null then satisfies a condition ( Contains() )
You need to create a predicate.
A function that will return true of false.
In you case:
.Where(***p => p.PalletMission == null || p.PalletMission.Destinations.Contains(currentGtpOrder.GtpStation.Node))
var result = list
.Where(p =>p.Property == null || p.Property?.SubPropertyList.Contains(1) == true);

Where condition equal true and Nullable object must have a value

I've been looking for an answer but I couldn't find anything to help me. I get this error
Nullable object must have a value.
My request is:
from e in dc.tblElements
where
e.IsUnique &&
(e.TypeID == 2) &&
(categoryId != null ? e.CategoryId.Value == categoryId.Value : true) &&
((e.Name.Contains(keyword)) ||
(e.Keywords.Contains(keyword)))
select e
The third line of the where condition is the problem (categoryId). If categoryId has a value, it works but not when it is null. However, I replaced this line with true and it works as well. I can't understand what is the problem here.
in my table CategoryId can be null so I tried:
(categoryId.HasValue && e.CategoryId.HasValue ? e.CategoryId.Value == categoryId.Value : true)
What I want to do: I want to select all the elements of this table depending on the where condition. categoryId comes from a drop down so if the default value is still selected when the user does the request, I want to display all the elements no matter what the category.
You should be good with just comparing your two variables:
e.CategoryId == categoryId
If you want special treatment of one being NULL, maybe because you want that to be a special case where NULL matches everything instead of just another NULL, you can add that:
e.CategoryId == categoryId || !e.CategoryId.HasValue || !categoryId.HasValue
Your problem with your statement is that you access .Value. Yes, if you would run the code with Linq-To-Objects in memory, it would work because the compiler will only run the code of one branch of your if-statement (ternary operator, I know, but you get what I mean). But for a database, there needs to be a statement prepared. That statement needs to be there in full, it does not use any short-circuiting. So the statement builder will access both your branches to build that statement for the database and one of those branches will fail because it accesses .Value although there is none.
Make CategoryId as nullable type and try.
Nullable<int> CategoryId = null;
Looks like you are trying to implement a "catch-all" categoryId parameter. That's an anti-pattern in SQL and a strong smell that can lead to bad performance.
In LINQ, it's not necessary since you can add .Where() conditions just by adding another .Where() call to your query, eg :
var query = from e in dc.tblElements
where
e.IsUnique &&
e.TypeID == 2 &&
( e.Name.Contains(keyword) ||
e.Keywords.Contains(keyword) )
select e;
if (categoryId.HasValue)
{
query=query.Where(e.CategoryId == categoryId);
}
You can use this to add multiple conditions at runtime
Try this:
from e in dc.tblElements
where
e.IsUnique &&
(e.TypeID == 2) &&
(categoryId.HasValue && e.CategoryId.Value == categoryId.Value) &&
((e.Name.Contains(keyword)) ||
(e.Keywords.Contains(keyword)))
select e

LINQ search query doesn't work

I'm trying to write a search query in LINQ. Below is the where condition.
where (!string.IsNullOrEmpty(nameWithInitials)
&& tb.NameWithInitials.Contains(nameWithInitials))
&& (!string.IsNullOrEmpty(studentRegNo)
&& tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (!string.IsNullOrEmpty(NIC) && tb.NIC.Contains(NIC))
&& (!string.IsNullOrEmpty(fullName) && tbi.Name.Contains(fullName))
It doesn't return any values if I pass a single parameter. For example if I pass 'Chamara' as fullname it doesn't return any result but if I pass all the parameters at the once then it returns the matching records.
I need to get this to work even when I pass several parameters dynamically
You are using AND (&&) everywhere, so if at least one of these conditions is false, your where condition will be false. Try using OR conditions instead:
where (string.IsNullOrEmpty(nameWithInitials) || tb.NameWithInitials.Contains(nameWithInitials))
&& (string.IsNullOrEmpty(studentRegNo) || tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (string.IsNullOrEmpty(NIC) || tb.NIC.Contains(NIC))
&& (string.IsNullOrEmpty(fullName) || tbi.Name.Contains(fullName))
In this case in any of these conditions if you have empty parameter, only the first part of condition will be evaluated, otherwise the second condition will be evaluated.
One potential issue is that Entity Framework might not be able to translate this to actual SQL. In this case, you can use such approach:
var query = // your original query without where condition
// Check if the condition is valid and only then add where condition
if(!string.IsNullOrEmpty(nameWithInitials))
{
query = query.Where(tb => tb.NameWithInitials.Contains(nameWithInitials));
}
// repeat this for all other conditions
What you're asking is semi-confusing but i think you want to search for every string if exists, which translates to
where ((string.IsNullOrEmpty(nameWithInitials)
|| tb.NameWithInitials.Contains(nameWithInitials))
&& (string.IsNullOrEmpty(studentRegNo)
|| tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (string.IsNullOrEmpty(NIC) || tb.NIC.Contains(NIC))
&& (string.IsNullOrEmpty(fullName) || tbi.Name.Contains(fullName))

How to make AND operator in C# linq?

IEnumerable<WireUsrTgInfo> lstWireData =
(from var in lstWireUsrTgInfo
where var.bWireData == true && var.bWireData == false --> This is not working
select var).AsEnumerable<WireUsrTgInfo>();
How to do this ...
according to the code provided
var.bWireData == true && var.bWireData == false
it can not work, as the same variable can not contemporary be equal to both oposite values.
if you need parametrize this, you can do it like :
bool expectedValue = true; //OR False
IEnumerable<WireUsrTgInfo> lstWireData = (from var in lstWireUsrTgInfo
where var.bWireData == expectedValue
select var).AsEnumerable<WireUsrTgInfo>();
EDIT
And don't use var in the query, it's contextual (as mantioned by Monkieboy) C# keyword. To be clear: you can use it, but you have to avoid doing that as it creates confusion.
bWireData cannot both be true AND false. There's a flaw in your logic.
As other answers stated, your filter condition is wrong. But there is something else I want to add:
Don't compare boolean data with true or false. Boolean data is actually an answer to question is it true or not.
var query = from info in lstWireUsrTgInfo
where info.bWireData // selects data which is true
select info;
Also var is a keyword;
Also do not use prefixes in variable names (consider better naming instead - HasWireData, wireUserTagInfos).
This will never work: WHERE bWireData == true && bWireData == false is illogical be cause bWireData can't be both true and false at the same time.
var is a keyword and to avoid confusion should therefor not be used as a name for a variable.
&& is the correct operator. However, as other posters have noted, your query as it stands is equivalent to saying "Make me happy if Obama is president and Obama is not president". Basically you have set up a contradiction, which will always evaluate to false and thus return no results. As an aside, you may be interested to learn that && is a conditional-and, meaning that the second term is only evaluated if the first term is true, thus saving the processing of second term if the result is inevitably false anyway.

Lambda vs LINQ- "Expression is always false"

I have the following code:
var thing = (from t in things
where t.Type == 1 && t.IsActive
select t).SingleOrDefault();
if (thing == null)
{
// throw exception
}
things is a collection of Entity Framework Self-Tracking Entities
This works nicely, however I want to use a Lambda expression instead and changed the LINQ to this:
var thing = things.Select(t => t.Type == 1 && t.IsActive).SingleOrDefault();
Now Resharper is telling me Expression is always false for (thing == null).
What have I missed?
You want:
var thing = things.Where(t => t.Type == 1 && t.IsActive).SingleOrDefault();
Select performs a projection (converting the type of the IEnumerable from IEnumerable<Thing> to IEnumerable<bool> with values true if t.Type == 1 && t.IsActive == true, otherwise false), then the SingleOrDefault returns either the only bool in this sequence, or the default value of a bool which is false if the sequence is empty. This can never be null since bool is not a reference type.
Where performs a filtering action (pulling out only those objects that meet a given criterion - in this case only selecting those where Type is 1 and IsActive is true), leaving the type of the IEnumerable as IEnumerable<Thing>. Assuming Thing is a class, the SingleOrDefault will return the only item in the sequence or null.
In either case, SingleOrDefault will throw an exception if the sequence contains more than one item (which is far more likely in the Select version!).

Categories