c# If Control in single row - c#

I am using asp.net mvc view , in order to use if control .
My Code:
<div class="panel-body #(((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == "" ? "collapse" : string.Empty)">
My Question about above if control:
I want to check
If ((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == null ||
If ((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == ""
I want to use ? "collapse" : else : string.Empty)">
How can i use If not null and If not "" in one row in my code?

If you're checking whether a string value is either null or "" then just use IsNullOrEmpty:
string.IsNullOrEmpty(((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus) ? "collapse" : string.Empty
If you want to combine multiple conditions in a conditional expression, you can do so with logical operators. For example:
if (someCondition && someOtherCondition)
This would require that both conditions be true. (If you use the || operator instead then it would require that at least one condition be true.)
So in a ?: operator that might look something like:
(someCondition || someOtherCondition) ? someValue : someOtherValue
Logical segments of conditional expressions can be grouped with parentheses, so you can include as many as you like:
(condition1 || (condition2 && condition3)) ? someValue : someOtherValue
Technically you can construct conditions and other expressions as large as you'd like, though of course code readability and maintainability becomes an issue pretty quickly. Extracting the logic into separate methods helps keep the code more organized.

Related

C# Null Conditional in Ternary condition

Am refactoring some old code and see something in the following format:
Type = rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"
which should not work if rec["IsFlagged"] is null, in which case I need to return null. How would one refactor to keep code in one line, if possible?
I can do something like but am wondering if the following can be achieved in one line to have minimal changes to code
if (rec["IsFlagged"] != null)
{
return rec["IsFlagged"].ToString() == "True" ? "Yes" : "No"
}
else
{
return null
}
Thanks,
The original code works fine.
rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"
The ? operator before .ToString() prevents the method from being called if null. The result of rec["IsFlagged"]?.ToString() would be null
Then, it compares null to "True" which is false (they are not equal).
The ternary operator then evaluates "No" and assigns it to the lvalue.
EDIT
So, now you want 3 possible results: "Yes", "No" or null. A single ternary only gives you two choices. There are many possibilities and yours is fine, unless you have multiple places doing something similar.
In that case, you could use an extension method:
public String CheckTrue(this object input) {
return input?.ToString() == "True" ? "Yes" : "No"
}
and then in your specific case:
return rec["IsFlagged"]?.CheckTrue()
Another alternative is to use multiple ternary operators?
return rec["IsFlagged"]==null ? null : (rec["IsFlagged"].ToString() == "True" ? "Yes" : "No");
This will do want you want..
rec["IsFlagged"]?.ToString().Replace("True","Yes").Replace("False","No")
.. but you perhaps shouldn't want to do it!
I prefer Garr's suggestions, though if it's a bool inside rec (is rec a DataRow?) I'd skip the ToString/compare with string and just use it as a bool once we know it's not null
return rec["IsFlagged"]==null ? null : ((bool)rec["IsFlagged"] ? "Yes" : "No");
But all in I like the extension method approach more, and we can tweak it some, leveraging conversion between a bool-or-null-stored-in-object and bool?:
public static string ToNullaboolString(this bool? x, string t = "Yes", string f = "No", string n = null){
if(x.HasValue)
return x.Value ? t: f;
return n;
}
Calling it like:
((bool?)rec["IsXxx"]).ToNullaboolString()
or supplying parameters if you want to change the strings returned (localization?)

how to insert if else in equal statement

I need to set the condition as below code.
_orderStatus = Request.QueryString["order"] != null ? Request.QueryString["order"] : _orderStatus != "" ? _orderStatus : "pending";
Currently the condition only applied to show pending order. How can i change and add to get as below condtion:
if Request.QueryString["order"] != null then
_orderStatus: "pending"
else
_orderStatus: "confirmed"
Thanks
should be like this
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
Additional note to the above answer: Let me copy your requirement to the answer:
if Request.QueryString["order"] != null then _orderStatus: "pending"
else _orderStatus: "confirmed"
Here you need to assign the result to the variable _orderStatus, The conditional operator will do that for you, you need not to do an additional assignment within the operator.
While using conditional operator if.. then can be replaced with ?
and else will be replaced by : and the result will be assigned to
the _orderStatus.
Now look into your code( which included in the answer), and apply the replacements as i said. then you will get the answer like the following:
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
The bets way of checking your query string then, try this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
There are multiple ways to do either u can simply check the for null or Empty by using if conditon like this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
or you can use conditional expression For reference u can go through this link
For your question u can use this way
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
There's no reason to expect any difference in performance.
In my opinion, the ternary operator should only be used if all three operands are very concise and easy to read. Otherwise I think it has the potential to make code harder to read.
I think a lot of people mis-use this operator by using too much logic into one long line of code. I personally won't use it unless the whole line is less than about 80 characters.

Order an if statement to ignore following tests if first test is null

I want to say if this property is (Null OR Equals "" OR contains "ImageNotAvailable") Then go ahead and do something. But when I try to use the code below, I get an object reference error. I was hoping by putting (Publisher.ThumbnailURL == null) at the beginning of the test, the other tests would be ignored, but I get error above.
if ((Publisher.ThumbnailURL == null) | (Publisher.ThumbnailURL == "") | (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
I can simply split these up into "If Else's" but is there a way to specify that if the first test is null, don't try and figure out the rest of the If statement which will cause it to error
Use || instead of |:
if ((Publisher.ThumbnailURL == null) || (Publisher.ThumbnailURL == "") || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
|| Operator
The conditional-OR operator (||) performs a logical-OR of its bool
operands, but only evaluates its second operand if necessary.
Note that you could also use string.IsNullOrEmpty as commented by Raphaƫl Althaus:
if (string.IsNullOrEmpty(Publisher.ThumbnailURL) || Publisher.ThumbnailURL.Contains("ImageNotAvailable"))
Yep, use || to evaluate the expression as early as possible, also, using String.IsNullOrEmpty would make the statement more brief:
if (String.IsNullOrEmpty(Publisher.ThumbnailURL) || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))

how do I convert if else to one line if else?

how do i convert follow code to one line if else
if (data.BaseCompareId == 2)
report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"));
else
report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
i try this code but did not work
data.BaseCompareId == 2
? report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"))
: report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Try with this instead :
string path = data.BaseCompareId == 2
? "~/Content/StimulReports/MonthGroup.mrt"
: "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
Since report.Load() returns a void, it wont work.
Edited version :
string s = data.BaseCompareId == 2
? "MonthGroup.mrt"
: "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + s));
I am assuming report.Load returns a void, hence it "doesn't work". That said, why are you doing this? The first example is perfectly clear.
If you want are going to use ?: here use it so only the part which is actually different is in the branching statement:
string fileName = (data.BaseCompareId == 2) ? "MonthGroup.mrt" : "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + fileName));
If you want to use a ternary operator, you can do:
report.Load(data.BaseCompareId == 2 ? Server.MapPath("~/Content/StimulReports/MonthGroup.mrt") : Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Or (better):
report.Load(Server.MapPath(data.BaseCompareId == 2 ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt"));
(Or you could further exploit the similarity in the two strings, as #helb's answer does.)
As has already been noted, your way doesn't work because you're trying to replace a conditional statement with a conditional expression, and conditional expressions have to have a value. Since report.Load apparently returns void, a conditional expression of the form cond ? report.Load(...) : report.Load(...) doesn't have a value, ergo it doesn't work.
Each of the ways above will work because the conditional expressions in them have values - in the first case, the value will be of the type returned by Server.MapPath; in the second case, the value will be of type string.
As to whether you should do this: there are arguments to be made either way. The original way has the advantage of being clear and simple, but it does involve some (arguably undesirable) repetition. The latter approach above has the advantage of only saying things once and emphasising the intent of the whole statement (to load a report), but it's arguably slightly less clear than the original, depending on how used people are to seeing conditional expressions. YMMV.
This syntax is just for cases where it returns something. So you could do something like:
var path = (data.BaseCompareId == 2) ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
This is the most concise I could get for a one-liner...
report.Load(Server.MapPath(string.Format("~/Content/StimulReports/{0}Group.mrt", data.CompareId == 2 ? "Month" : "Year")));
However, it seems you just want to make things look cleaner.
More abstraction between data calls and the conditional logic.
You might want to consider making them separate methods, perhaps on your report object?
if(data.CompareId == 2)
report.LoadStimulReports(ReportGroup.Month);
else
report.LoadStimulReports(ReportGroup.Year);
Using an enum, extension method, and static method on your report object...
public enum ReportGroup
{
[DescriptionAttribute("~/Content/StimulReports/MonthGroup.mrt")]
Month,
[DescriptionAttribute("~/Content/StimulReports/YearGroup.mrt")]
Year
}
public static T GetAttribute<T>(this Enum e) where T : Attribute
{
System.Reflection.FieldInfo fi = e.GetType().GetField(e.ToString());
object[] o = (object[])fi.GetCustomAttributes(typeof(T), false);
return o.Length > 0 ? (T)o[0] : default(T);
}
public static void LoadStimulReports(ReportGroup reportGroup)
{
report.Load(Server.MapPath(reportGroup.GetAttribute<DescriptionAttribute>().Description));
}
Now you can simply add another item to the enum if you need another report.
[DescriptionAttribute("~/Content/StimulReports/WeekGroup.mrt")]
Week

What is this confusing expression "a == b ? value1 : value2"?

I am new to learning C# and Silverlight and have been given some application files by my employer to start learning. I am able to understand most of the logic, methods and syntax used in C# but there is one line which is very confusing to me. I dont have access to my seniors right now to ask them so the logic behind it so I thought I will ask here.
Take a look at this:
In a .xaml.cs file:
List<object> lst = new List<object>();
lst.Add(GP.mpl.A);
lst.Add(GP.mpl.B);
lst.Add(GP.mpl.C);
lst.Add(GP.mpl.StnNo);
In a different .cs file:
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
I understand that StnNo is being received from lst[3] and converted to Integer through
Convert.ToInt32(lst[3].ToString()
But I dont understand this part:
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString())
Could you tell me what's going on there? I have done multiple searches on google but didn't find anything related. Thanks for any help.
? is a ternary operator.
condition ? first_expression : second_expression;
?: Operator (C# Reference)
So in you example,
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
is equal to
public int StnNo;
if (lst[3].ToString() == string.Empty)
{
StnNo = 0;
}
else
{
StnNo = Convert.ToInt32(lst[3].ToString());
}
This is the conditional, sometimes referred to as ternary, operator.
It takes the form boolean expression ? true value : false value.
In C#, the true value and false value must be of the same type, or one must be implicitly convertible to the other (but not both). Otherwise, you must legally and explicitly cast one or both to a common type.
In your code, you have
int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
it is producing the functional equivalent of
int temp;
if (lst[3].ToString() == string.Empty)
temp= 0;
else
temp = Convert.ToInt32(lst[3].ToString());
int StnNo = Convert.ToInt32(temp);
You can see the outer Convert.ToInt32 in your code is actually redundant and can be eliminated.
int StnNo = lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString());
That's a very poorly written way of saying "if lst[3] is empty, then use 0, otherwise parse lst[3]" - because as your question illustrates, it's harder to tell what exactly the original developer intended.
To make it more clear, let's dissect it.
lst[3].ToString() == string.Empty means "does the lst[3] evaluate to an empty string?"
? X : Y means "if so, X, otherwise Y.
0 a constant value
Convert.ToInt32(lst[3].ToString()) parses the value as an lst[3] integer.
Finally the whole expression is passed into another Convert.ToInt32, but this is entirely unnecessary because the result of the conditional expression is always an int.
Since you don't have to call Convert.ToInt32 twice, a better way of writing this would be:
public int StnNo =
(lst[3].ToString() == string.Empty
? 0
: Convert.ToInt32(lst[3].ToString()));
An even better way of writing this would be:
int StnNo;
int.TryParse(lst[3], out StnNo);
It's more lines of code, but it's a lot easier to read.
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()) is to check that if lst[3] does not contain any value, then 0 will be assigned to StnNo.

Categories

Resources