C# 获取 DisplayName 的首字母缩写

RyR*_*lli 3 c# backend dto

我正在尝试从显示名称中提取缩写以用于显示其缩写。我发现这很困难,因为字符串是包含一个或多个单词的一个值。我怎样才能实现这个目标?

例子:

'约翰·史密斯' => JS

“史密斯,约翰”=> SJ

'约翰' => J

“史密斯”=> S

public static SearchDto ToSearchDto(this PersonBasicDto person)
        {
            return new SearchDto
            {
                Id = new Guid(person.Id),
                Label = person.DisplayName,
                Initials = //TODO: GetInitials Code
            };
        }
Run Code Online (Sandbox Code Playgroud)

我使用了以下解决方案:我创建了一个帮助器方法,它允许我测试多种情况。

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;
        }
Run Code Online (Sandbox Code Playgroud)

AAA*_*ddd 10

或者只是作为扩展方法的另一种变体,带有少量的健全性检查

给定

public static class StringExtensions
{
   public static string GetInitials(this string value)
      => string.Concat(value
         .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
         .Where(x => x.Length >= 1 && char.IsLetter(x[0]))
         .Select(x => char.ToUpper(x[0])));
}
Run Code Online (Sandbox Code Playgroud)

用法

var list = new List<string>()
{
   "James blerg Smith",
   "Michael Smith",
   "Robert Smith 3rd",
   "Maria splutnic Garcia", 
   "David Smith", 
   "Maria Rodriguez",
   "Mary Smith", 
   "Maria Hernandez"
};

foreach (var name in list)
   Console.WriteLine(name.GetInitials());
Run Code Online (Sandbox Code Playgroud)

输出

JBS
MS
RS
MSG
DS
MR
MS
MH
Run Code Online (Sandbox Code Playgroud)

完整演示在这里