0

I have this helper method on an MVC View that returns the first name and last name of the user (Windows autheticated application)

@helper AccountName()
{
    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
        @principal.GivenName<text> </text>@principal.Surname
    }
}

How can I extract the initials of the user(first letter of first name and first letter of last name)?

I tried with linq:

@AccountName().ToString().Split(' ').Select(x => x[0]).ToArray()

But that results:

System.Char[]

Any help would be appreciated

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user3378165
  • 6,546
  • 17
  • 62
  • 101
  • That character array contains the first letter of first and last name.. you already have your own answer – EpicKip Aug 21 '18 at 10:49

3 Answers3

2

If you want to output the first letters as a string instead of a character array (in order to make the ToString work), use the string constructor. This is already mentioned here.

However, to make that work, you do need to wrap this in a code block (@(...)). Then it wil print correctly.

@(new string(@AccountName().ToString().Split(' ').Select(x => x[0]).ToArray()))
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

I would use a neat Regex;

// This could be compiled and cached.
var initialsRegex = new Regex(@"(\b[a-zA-Z])[a-zA-Z]*\.* ?"); 

// This gives the initials
var initials = initialsRegex.Replace(AccountName, "$1");

This will also include names that contain initials with . i.e. John S. Doe

tigerswithguitars
  • 2,497
  • 1
  • 31
  • 53
0

You can try this too

foreach (string s in @AccountName.Split(" ".ToCharArray()))
    shortName += s.Substring(0,1).ToUpper();
R15
  • 13,982
  • 14
  • 97
  • 173