N00bTech
N00bTech

Reputation: 11

What's the best way to write an if statement that makes a string equal to something else

I'm working on a project and need to set old data starting with a 0, 1, or 2 to simply equal a level.

if (dr["Acct"].ToString().Substring(0,1) == "0"
    || dr["Acct"].ToString().Substring(0,1) == "1"
    || dr["Acct"].ToString().Substring(0,1) == "2")
{
    // then Level = Balance Sheet
}

I am essentially trying to say if the substring is 0, 1, or 2, then it should equal the level called Balance Sheet.

Upvotes: 0

Views: 86

Answers (3)

MustangManiac
MustangManiac

Reputation: 317

If you have want to check multiple strings i would store in string array and check it for better readability

public string[] dataStartsWith= {"0","1","2"};

if(dataStartsWith.Contains(dr["Acct"].ToString().Substring(0,1))){
    Level = "Balance Sheet"
}

Upvotes: 2

Ben Matthews
Ben Matthews

Reputation: 531

String operations are expensive, and this is probably a more readable way to go about it.

string acctVal = dr["Acct"]?.ToString();
char[] balanceSheetVals= {'0', '1', '2'};

if(!String.IsNullOrEmpty(acctVal))
{
   if(balanceSheetVals.contains(acctVal[0]))
   {
      Level = "Balance Sheet";
   }
   else
   {
      //defaults
   }
}
else
{
   //defaults
}

Edit: Most props to @Rotem who cleaned this up a lot

Upvotes: 2

Joshua Robinson
Joshua Robinson

Reputation: 3539

If you want to check if some string starts with some other string, I personally find String.StartsWith to be more readable and more clearly state the intent of the code than using String.Substring.

var target = dr["Acct"].ToString();
if (target.StartsWith("0")
   || target.StartsWith("1")
   || target.StartsWith("2")
)
{
   Level = "Balance Sheet";
}

Upvotes: 2

Related Questions