I have a condition as shown below:
x.Customer == null ? false : x.Customer.CustomerData.IsSet
My IDE is saying to Simplify conditional ternary expression. Is there any other way to simplify this in dotnet? I recently started working with c# world it so kinda confuse on this.
Also can we also add a null check CustomerData too just like I have for Customer in a single line as well?
I tried like this -
Field("isSet", x => x.Customer?.CustomerData?.IsSet ?? false);
When I try this, it gives an error as -
An expression tree lambda may not contain conditional access
expression
The result of your expression is boolean so there's no need to write ternary operator. You can write it this way:
x.Customer != null && x.Customer.CustomerData.IsSet
Just try
bool result = x.Customer?.CustomerData?.IsSet ?? false
So if any of Customer or CutomerData is null, default will be false, otherwise IsSet will be returned.
Related
This question already has answers here:
Question mark and colon in statement. What does it mean?
(7 answers)
Closed 5 years ago.
I found a piece of code online where there is this line:
new Claim(JwtClaimTypes.EmailVerified,
user.EmailConfirmed ? "true" : "false",
ClaimValueTypes.Boolean)
While the code works I'm not sure what does that specific line do. I know the "?" symbol is used to nullify Types, but can it be used to cast Types as well?
It is not for casting. It is just the conditional operator, an easy syntax to do an if-else code block. So if the expression before ? returns true, it executes the first expression ( the one followed by ?) and return the value and if the expression before ? returns false, it returns the return value of the second expression (followed by :)
So in your case, If the value of the expression user.EmailConfirmed is true the code will be same as
new Claim(JwtClaimTypes.EmailVerified, "true" , ClaimValueTypes.Boolean)
else (if it is false)
new Claim(JwtClaimTypes.EmailVerified, "false" , ClaimValueTypes.Boolean)
You can also call the ToString() method on the boolean value and then call ToLower() method to get true or false . If you ever want to try that, Here is how you do it
new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed.ToString().ToLower(),
ClaimValueTypes.Boolean)
I would personally prefer the first approach ( conditional operator), but probably replace the magic strings with some constants
I have been reading up Expression trees, and I think this is a good example to use them, still I can't seem to grasp how this would be done.
I have a set of strings that I want evaluated, they are all of the type:
exp == exp , or exp != exp , or exp (<,>,>=,<=) exp if exp is Numerical Type.
The exp do not need to check if they are valid I am fine with them blowing up if they are not.
My issue is, how to I parse to get the actual obj.
I want to pass a string like these below
Owner.Property.Field == 3;
or
Owner.Field == 3;
or
Owner.Method(1) == true
And get if the evaluation is true or not. MY issue is how do I travel down the "path" on the left and get the value?
I implemented a version with Reflection and string parsing, that somehow does the work - except for when we are using a method, and honestly its not that performant at all. I want this to be as performant as possible can get, and if possible give me a small explanation of how the expression works , so I can learn.
You can use code generation libraries like CodeDOM or Roslyn to generate Func that will do the evaluation.
For example, in Roslyn you can create a Session and set an object containing Owner as the Host object of the Session. than you can generate the code in the Session as you wish like the following:
Session session = ScriptEngine.CreateSession(objectContainingOwnerAsProperty);
bool result = session.Execute<bool>("Owner.Field == 8");
Now result will contain the evaluation result for your string without reflection nor string analysis.
I'm trying to figure out how to have a short, one line conditional statement.
If this date is not null, add the filter to the current list of filters:
fromDt ?? filters.Add(FilterType.DateFrom, fromDt);
Is there a way to do this? I know I could do..
(fromDt != null) ? "something" : "something_else", but I don't need the 'else', and would really like to just use the ?? operator for null checking.
What's wrong with this?
if (fromDt != null) filters.Add(FilterType.DateFrom, fromDt);
First and foremost, your code should be readable. Even if your ?? code works, I wouldn't know what it does on first glimpse.
The code you are attempting makes your code very difficult to read. Like BrokenGlass said, you are trading clarity for raw character count.
This is the only "one line" solution C# supports.
if (fromDt != null) filters.Add(FilterType.DateFrom, fromDt);
But I encourage everyone to expand this to at least two lines (my preference is four with the braces).
Purpose of the solution aside, following one-liner might give you end result you want while using ??. Do not try this at home though.
filters.Add(FilterType.DateFrom, fromDt ?? DateTime.MinValue)
The idea is to set DateFrom to min possible value, essentially adding an open filter.
I was wondering if there is an easy way to place two Lambda expressions in a single (Linq/Where) query?
For example, I currently call a method with something like the following:
string testing = "blablabla";
if(testing == "" || testing == null)
I have tried a few combinations such as:
testing.Where(x => x == ("") || x=> x == null);
But the above doesn't work. I know I can set up a method that returns a predicate/bool, but, at the moment, I am interested in Lambdas and was just wondering how to achieve this.
Do I need to chain multiple Where methods, or is there a way to achieve multiple Lambdas?
(p.s. I know about IsNullOrEmpty, this is just the first example I could think of!)
You can always combine them to a single lambda.
testing.Where(x => x == null || x == ("") );
If you're looking for a general way to combine query conditions in arbitrary ways, you can use expression trees:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
I found this article on the webs and thought I'd try to apply the null string style method to my excel range value. Sometimes it has a value in it and sometimes it doesn't and obviously double doesn't like null values.
This is my little snippet.
double valTotal = (rngTotal.Value != null ? 1 : 0);
My question is what am I doing with this above code? It looks like an if statement in one line with the "1" being the "then" and the "0" being the "else". Is that right? And most importantly, what is the name of this syntax so I can find out more about this?
It's the conditional operator. (Sometimes incorrectly called the ternary operator; it's a ternary operator as it has three operands, but its name is the conditional operator. If another ternary operator is ever added to C#, "the ternary operator" will become an ambiguous/non-sensical phrase.)
Quick description:
The first operand is evaluated, and if the result is true, the second operand is evaluated and forms the overall value of the expression. Otherwise the third operand is evaluated and forms the overall value of the expression.
There's a little more detail to it in terms of type conversions etc, but that's the basic gist.
Importantly, the first operand is always evaluated exactly once, and only one of the second or third operand is evaluated. So for example, this is always safe:
string text = GetValueOrNull();
int length = text == null ? 5 : text.Length;
That can never throw a NullReferenceException as text.Length isn't evaluated if text == null is true.
It's also important that it's a single expression - that means you can use it in some places (such as variable initializers) where you couldn't use the if/else equivalent.
Closely related is the null-coalescing operator which is also worth knowing about.
It's the conditional operator:
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
This is known as the conditional / ternary operator in C#. It's essentially short hand for the following
double valTotal;
if (rngTotal.Value !=null) {
valTotal = 1;
} else {
valTotal = 0;
}
It is the conditional operator. Yes, it acts like an "inline if". It is a handy shortcut for short if expressions. The part before the '?' is a Boolean condition if the Boolean condition is true then the part after the '?' is evaluated otherwise the part after the ':' is evaluated. In other words the '?' and ':' act like the 'then' and 'else' in an if statement.
See the links below for more detail.
https://msdn.microsoft.com/en-us/library/ty67wk28.aspx
The ternary (conditional) operator in C
It's called conditional operator:
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx