Conditional Statement Checking Null - c#

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.

Related

How to compare inexact string values

I want to compare two string values which are not exact For example I want to compare Admin to Administrator, this should return true or should execute.
I tried contain which is not working
var prodcut = lstProducts.Where(i => i.Name.ToLower().Contains(appname.ToLower())).FirstOrDefault();
Above code not working if i.Name is 'Admin' and appname.ToLower() is 'Administrator'. It just return null but want it should detect values.
If you want to check it both ways so if A contains B OR if B contains A you can use the || operator (the OR operator) like so:
a.Contains(b) || b.Contains(a)
You've got the strings the wrong way around (you're looking for Adminstrator in Admin)
You can do the check both ways around like this:
lstProducts.Where(i =>
i.Name.ToLower().Contains(appname.ToLower()) ||
appname.ToLower().Contains(i.Name.ToLower())
).FirstOrDefault();
Or just compare the first few characters:
lstProducts.Where(i =>
i.Name.ToLower().SubString(0,5) == appname.ToLower().SubString(0,5))
).FirstOrDefault();
Fuzzy matching is actually quite a complicated subject but there's a lot of research into the topic.

Conditional breakpoint not working

The above code has a conditional breakpoint set at its bottom line in yellow followed by the Breakpoint Settings dialog which should work with:
item.Value == "aday"
However I get the below error, I have searched online for this and can't find any reason why this should fail. Im using VS 2015 Pro.
EDIT- Thank you for pointing out the obvious error on my part, I do normally code in C#.
But now using a single '=' I get this???????
I assume that I it equates to an assignment, and adding parenthesis didn't help either?
Just tested with a sample VB.NET project.
The problem is the ==. This is C# syntax but since you have a VB.NET application you should use a single equal
item.Value = "aday"
(I have always something new to learn from SO)
If item.Value.Equals("aday") Then 'Temp If please remove
Debugger.Break()
end if
Actually works in strict mode, Gasp!!!!
Thanks to all contributions, greatly appreciated :)
I am using the C# in Visual Studio 2017.
After search in an hour, conclusion was:
rewrite the conditional expression from:
item.Value == "aday"
to:
item != null && item.Value == "aday"
MAKE SURE item was not null. so that you can refer to field of value with item.Value

How to evaluate a simple C# string

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.

In System.Linq.Dynamic.Select(), how to deal with a null object reference in a simple way?

I am using dynamic LINQ (System.Linq.Dynamic)(you may find description here, http://dynamiclinq.azurewebsites.net/GettingStarted).
The following statement works well
Products.Select("new(ProductName, CategoryID.CategoryName as CategoryName)");
But I accidentally found when CategoryID is null, the results are empty. But I supposed it would return a record such as:
ProductName="Wine", CategoryName="" (or null).
Then I found a way to do so by
Products.Select("new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)");
The statement is ugly.
Do you have a better solution?
Thank you in advance,
The only thing I found is here. It isn't clear why the solution was accepted, but what I did see there is that you can do this:
"new(ProductName, iif(CategoryID==null,null,CategoryID.CategoryName) as CategoryName)"
instead of this:
"new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)"
It isn't any shorter, but to me it makes the code a bit more readable because you just use null instead of escaping the quotes.

Why checking for null before comparing a value to a constant?

Sometimes, a value must be checked for equality with a constant. In such cases, I've always seen the code like this:
if (!string.IsNullOrEmpty(text))
{
if (text == "Some text here")¹
{
// Do something here.
}
}
In my case, I would rather write:
if ("Some text here".Equals(text))
{
// Do something here.
}
After all, if text is null, Equals will return false, which is expected. The inversion of a constant and a variable feels strange, but is still understandable for a beginner, and avoids the NullReferenceException which would be thrown with text.Equals("Some text here").
Am I missing something?
Why all source code I've seen use the syntax from the first example, and never from the second one?
¹ In real code, it would rather be a constant or a readonly field. To shorten the examples, I put the strings inline.
In such cases, I've always seen the code like this:
You're right to think that's odd and unnecessary, because it is. It's a completely superfluous null or empty check. Frankly, I'd admonish code like that in a code review.
if (text == "Some text here") {
// Do something here.
}
is perfectly fine and that's what I'd use.
Am I missing something?
No, you're not missing anything.
Why all source code I've seen use the syntax from the first example, and never from the second one?
Because you're looking for love in all the wrong places?
There is nothing wrong with just this.
if (text == "Some text here")
{
// Do something here.
}
There is no need to check for null/empty, since it won't be equal anyway.
If you wish to use the Equals method, there is a version that isn't sensitive to null values.
if (string.Equals(text, "Some text here"))
{
// Do something here.
}
Your version is fine so long as you have a literal or something that you know will not be null.
If, on the other hand, you had
if (text1.Equals(text2))
then clearly you would need to defend against text1 being null.
But I would stop using Equals here and use == which removes the need for the null check
if (text1 == text2)
Are you preferring to use Equals because of your Java roots?
I would think it is in human nature, when you compare smth, you always compare "your" stuff against someone else. not the other way around, i think same natual thinking went to C# coding as well :)
I would just use if (text == "Some text here"). It's clear, concise, and fast. The IsNullOrEmpty check you refer to might be a (most likely useless) micro-optimization.

Categories