I apologize for the vague title but I wasn't really sure the best way to describe it.
I am writing a C# transform script in SSIS. The goal is to take in 5 values which are decimals, and I need to receive the first value out of 5 that is not null, in a predetermined order as you can see by the order of the else if statements. So as you can see I want to grab the MM value if it has one, if not then the PRE, then DD, PT, etc. You'll also see I just assign a little varchar label value to show which value came back as well.
Is there a cleaner/easier way of doing this that doesn't include a bunch of if/else if blocks? I'm just looking to clean it up.
current code below (Thanks for any advice!):
public Tuple<decimal?,string> getCurrentRec(Decimal? PT, Decimal? DD,
Decimal? PRE, Decimal? MM)
{
string ptlabel = "PT";
string ddlabel = "DD";
string prelabel = "PRE";
string MMLabel = "MM";
string curlabel;
decimal? currentval;
if (MM.HasValue)
{
curlabel = MMLabel;
currentval = MM.Value;
}
else if (PRE.HasValue)
{
curlabel = prelabel;
currentval = PRE.Value;
}
else if (DD.HasValue)
{
curlabel = ddlabel;
currentval = DD.Value;
}
else if (PA.HasValue)
{
curlabel = ptlabel;
currentval = PT.Value;
}
else
{
curlabel = "";
currentval = (decimal?)null;
}
return Tuple.Create(currentval, curlabel);
}
One possible way:
var match = new[] {
new {v = MM, n = nameof(MM) },
new {v = PRE, n = nameof(PRE) },
new {v = DD, n = nameof(DD) },
new {v = PT, n = nameof(PT) },
}.FirstOrDefault(c => c.v != null);
return Tuple.Create(match?.v, match?.n ?? "");
You create array of anonymous types with 2 properties: v
for value of your decimal and n
for corresponding label. Items in array should be in correct order. Then you use FirstOrDefault
to find first element which has non null value.