[ACCEPTED]-LINQ: Get first character of each string in an array-string
Accepted answer
try this:
string shortName = new string(someName.Select(s => s[0]).ToArray());
or, if you suspect that any of 1 the strings might be empty or so:
string shortName = new string(someName.Where(s => !string.IsNullOrEmpty(s))
.Select(s => s[0]).ToArray());
string[] someName = new string[] { "First", "MiddleName", "LastName" };
String initials = String.Join(".",someName.Select(x => x[0].ToString()).ToArray());
Produces
F.M.L
0
This solution accounts for empty strings 1 as well by removing them from the output
var shortName = new string(
someName
.Where( s => !String.IsNullOrEmpty(s))
.Select(s => s[0])
.ToArray());
string initials = someName.Where(s => !string.IsNullOrEmpty(s))
.Aggregate("", (xs, x) => xs + x.First());
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.