考虑一个形状如下的字符串数组:
string[] someName = new string[] { "First", "MiddleName", "LastName" };
要求是从数组中的每个元素获取第一个字符。
即
FML
以前尝试过:
string initials = string.Concat(someName.Select(x => x[0]));
问题:您会编写什么LINQ查询来连接字符串数组中包含的所有名称以提供缩写?
答案 0 :(得分:24)
试试这个:
string shortName = new string(someName.Select(s => s[0]).ToArray());
或者,如果您怀疑任何字符串可能是空的,那么:
string shortName = new string(someName.Where(s => !string.IsNullOrEmpty(s))
.Select(s => s[0]).ToArray());
答案 1 :(得分:7)
string[] someName = new string[] { "First", "MiddleName", "LastName" };
String initials = String.Join(".",someName.Select(x => x[0].ToString()).ToArray());
可生产
F.M.L
答案 2 :(得分:7)
此解决方案通过从输出
中删除它们来解释空字符串var shortName = new string(
someName
.Where( s => !String.IsNullOrEmpty(s))
.Select(s => s[0])
.ToArray());
答案 3 :(得分:0)
string initials = someName.Where(s => !string.IsNullOrEmpty(s))
.Aggregate("", (xs, x) => xs + x.First());
答案 4 :(得分:-2)
string[] someName = new string[] { "First", "MiddleName", "LastName" };
someName.FirstOrDefault();