-3

in one of our templates for report printing there is the following code:

 if (!string.IsNullOrEmpty(assetModel.Belongings)) { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty(description) ? "" : ", ", assetModel.Belongings); } 

I would like to test the first character of the Belongings field. if it IS NOT a "," then the code above should be used but if it IS a "," the code should be like:

 if (!string.IsNullOrEmpty(assetModel.Belongings)) { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty(description) ? "" : "", assetModel.Belongings); } 

Please help, how can I test this value of the first character?

1

2 Answers 2

4

Method StartsWith is self-explaining:

if (description.StarstWith(",")) { //... } 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this is the solution I was looking for, and this is the result. Sorry, can't get the code shown in the right way. if (!string.IsNullOrEmpty(assetModel.Belongings)) {if (assetModel.Belongings.StartsWith(",")) { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty(description) ? "" : "", assetModel.Belongings); } else { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty(description) ? "" : ", ", assetModel.Belongings); } }
0

Use IndexOf to check if the index of the , character is 0, meaning it's at the start of the string.

if (description.IndexOf(',') == 0) { // description starts with a , } 

4 Comments

It should work, but IndexOf isn't build for this purpose. In my optinion StartsWith() would be better in this context.
Searching whole string instead of just checking description[0]==','?
@Jannik true, didn't think of StartsWith until after I posted.
@Steve I feel you, I was about to post a substring-alternative, well, there are many different roads to reach the same goal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.