My problem is that I have a sequence, potentially infinite, of strings. Let's suppose it to be
{"Mickey Mouse", "Bugs Bunny", "Winnie the Pooh"}
I have to make an exthension-method Initials that returns a sequence of their capital letters in uppercase, so in this case, doing:
var names = new string [] {"Mickey Mouse", "Bugs Bunny", "Winnie the Pooh"}
foreach (var cl in names . Initials ())
Console.WriteLine(cl);
returns, in order, MM, BB, WTP. Note that whitespaces have not to be considered.
After hours of staring at the screen, i managed to write this not so goodlooking code:
public static IEnumerable<string> Initials(this IEnumerable<string> names)
{
var res = new List<string>();
var listOfArrayOfStrings = names.Select(s => s.Split());
foreach (var arrayOfStrings in listOfArrayOfStrings)
{
string newString = "";
foreach (var singleString in arrayOfStrings)
{
if (!string.IsNullOrWhiteSpace(singleString)) //no whitespaces
{
var temp = char.ToUpper(singleString[0]).ToString(); //first upper String
newString += temp;
}
}
res.Add(newString);
}
return res;
}
Then, my disliked R# suggested me to do some refacory and then it became the following:
var listOfArrayOfStrings = names.Select(s => s.Split());
return listOfArrayOfStrings.Select(arrayOfStrings =>
(from singleString in arrayOfStrings
where !string.IsNullOrWhiteSpace(singleString)
select char.ToUpper(singleString[0]).ToString())
.Aggregate("", (current, temp) => current + temp))
.ToList();
Now, I have two questions about this:
Is this, in your opinion, a good way to reach my aim?
I will have to do a written test where I'll have to do something like that. How can I "guess" something like that without R#? I mean, I'm still having difficulties understanding all that Linq stuff. Have you got any idea to how I can approach problems like this? Often these test are about managing
IEnumerables, so Linq could be very helpful, but I rarely understand the right sequence of Linq queries.