I'm trying to extract initials from a display name to be used to display their initials. I'm finding it difficult because the string is one value containing one word or more. How can I achieve this?
Example:
'John Smith' => JS
'Smith, John' => SJ
'John' => J
'Smith' => S
public static SearchDto ToSearchDto(this PersonBasicDto person)
{
return new SearchDto
{
Id = new Guid(person.Id),
Label = person.DisplayName,
Initials = //TODO: GetInitials Code
};
}
I used the following solution: I created a helper method which allowed me to test for multiple cases.
public static string GetInitials(this string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
string[] nameSplit = name.Trim().Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
var initials = nameSplit[0].Substring(0, 1).ToUpper();
if (nameSplit.Length > 1)
{
initials += nameSplit[nameSplit.Length - 1].Substring(0, 1).ToUpper();
}
return initials;
}