-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?

Fred
  • 1
  • 1
  • 3
    you can use [String.StartsWith](https://msdn.microsoft.com/en-us/library/baketfxw(v=vs.110).aspx) – bansi Dec 21 '15 at 07:48

2 Answers2

4

Method StartsWith is self-explaining:

if (description.StarstWith(","))
{
    //...
}
Backs
  • 24,430
  • 5
  • 58
  • 85
  • 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); } } – Fred Dec 21 '15 at 10:30
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 ,
}
Steve
  • 9,335
  • 10
  • 49
  • 81