Using "And" operator comparing three variables - c#

if (dr["programmeCode"].ToString() == (combo_Programme.ToString())) &= (dr["Actions_ProgrammeDerivedCode"].ToString()) = null;
Can anyone help and explain why my "And" expression "&=" (or "&&") will not work in the above expression ?

you cand do the following..
if (dr["programmeCode"].ToString() == combo_Programme.ToString()
&& string.IsNullOrEmpty(dr["Actions_ProgrammeDerivedCode"].ToString()))
{
}

I am not sure what you are trying to do and neither is the computer. I am assuming your code is all part of the logical statement.
The &= assigns a value to the variable on the left of it. So in your case, you would be trying to assign (dr["Actions_ProgrammeDerivedCode"].ToString() to the if statement!
You meant to use the && operator, then you might note that your parentheses exclude the statement from the logical test. You need to add more parentheses and change the = null to == null or it will also try to assign:
if ((dr["programmeCode"].ToString() == combo_Programme.ToString())
&& (dr["Actions_ProgrammeDerivedCode"].ToString() == null)) {
do something...
}
Here is a link to some helpful documentation on variable assignment:
https://msdn.microsoft.com/en-us/library/e669ax02.aspx
Here is a link to some helpful documentation on if statements:
https://msdn.microsoft.com/en-us/library/5011f09h.aspx

Related

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

How to use multiple lines in .OrderBy in c#?

I have this code
folderList = (List<SPFolder>)folderList.OrderBy(folder => Object x = folder.GetProperty("Order Folder By"); x == null ? 0 : (int)x;).ToList();
But it's giving me a syntax error.
Does anyone know whats wrong here?
Thanks.
You're not returning anything. You need to return the value in a statement lambda. You also need to wrap the statements in curly braces to use multiple statements in a lambda. You also can't treat a conditional operator as an expression; it needs to be a statement.
They're fixed with the same fix.
folderList = (List<SPFolder>)folderList.OrderBy(folder => {
Object x = folder.GetProperty("OrderFolderBy");
return x == null ? 0 : x;}).ToList();
That said, you can do the whole thing with just an expression instead; there's no need to use multiple statements:
folderList = folderList.OrderBy(folder => folder.GetProperty("OrderFolderBy") as int?).ToList();
There also no reason for that cast. The list should already be of the appropriate type, and both null and 0 come before other numbers, so there's no real reason for the null check at all.
You need the braces since you had two statements in the lambda and you also need the cast to object for the ? : operator
folderList = folderList.OrderBy(
folder =>
{
Object x = folder.GetProperty("OrderFolderBy");
return x == null ? (object)0 : x;
}).Cast<SPFolder>().ToList();
You can avoid using the intermediate assignment to x by using the null coalescing operator ??.
folderList = folderList.OrderBy(
folder => folder.GetProperty("OrderFolderBy") ?? (object)0)
.ToList();

Clean way to check for Null in Lambda Expressions

I have seen a lot of questions on this but was not able to find a clean solution:
I have the following lambda expression:
var result = Store.FirstOrDefault(x.Products.Coupon[0] == 100);
I would like to check for null for the Coupon collection to check to see if its not null and then compare the first coupon with the value 100. What would be a clean way to check for NULL for Coupon in the lambda? I do not want to use an extension method to check for null. I would like to do the check inline.
var result = Store.FirstOrDefault(x => x.Products.Coupon != null && x.Products.Coupon.Any() && x.Products.Coupon[0] == 100);

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.

LINQ query, ignoring results with certain decimal points

I need to perform a LINQ query on a large database in C#. One of the columns I need to use in the query is a double. I need to omit results that have more than 4 decimal places in this column. The database can't be changed as other programs need to use it and make use of what I don't want. The results are then added to a list to use later. I thought that this would work.
where fun.Units != '*.?????*'
However it returns the error that too many characters are in the character literal.
The whole query looks like this so far
var clientQuery1 = from cli in main1.Clients
from pol in main1.Policies
from fun in main1.FundHoldings
from uni in main1.UnitPrices
where cli.AccountNumber == accNum
&& pol.ClientRef == cli.ClientRef
&& fun.FKeyRef == pol.PolicyRef
&& uni.UnitPriceRef == fun.UnitPriceRef
&& fun.Units != '*.?????*'
select uni.UnitName;
Can you please try with this below query and let me know.
var clientQuery1 = from cli in main1.Clients
from pol in main1.Policies
from fun in main1.FundHoldings
from uni in main1.UnitPrices
where cli.AccountNumber == accNum
&& pol.ClientRef == cli.ClientRef
&& fun.FKeyRef == pol.PolicyRef
&& uni.UnitPriceRef == fun.UnitPriceRef
&& fun.Units == Math.Round(Convert.ToDouble(fun.Units),4)
select uni.UnitName;
Well you can solve that particular error using:
&& fun.Units != "*.?????*"
Note the change from single quotes to double quotes. However, that's not going to help you overall. What's the type of fun.Units in LINQ? If it's decimal, you might be able to use:
&& decimal.Round(fun.Units, 4) == fun.Units
... but it's not clear to me what that will do in the generated SQL. It's worth a try, but even if it works you should see what the SQL looks like.

Categories