The classic version, as taught in schools:
public int SumOfShortestAndLenghtiestWord(string[] words) { if (words.Length == 0) throw new Exception("N/a to empty array."); var min = 0; var max = 0; bool isFirstWord = true; foreach (var word in words) { if (isFirstWord) { min = word.Length; max = word.Length; isFirstWord = false; continue; } if (word.Length > max) max = word.Length; if (word.Length < min) min = word.Length; } //min.Dump(); //max.Dump(); return min + max; }
Suppose in this case min = 2, max = 11 sum - 13:
var source = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"; var result = SumOfShortestAndLenghtiestWord(source.Split(' '));
And this option is good because the detour is performed only once.
You can also write a variant based on linq:
public int SumOfShortestAndLenghtiestWord(string[] words) { if (words.Length == 0) throw new Exception("N/a to empty array."); var min = words.Min(x => x.Length); var max = words.Max(x => x.Length); return min + max; }
Compact, easy to read, you can shrink to the one-liner.
Update. Here in the comments they hint that the most canonical version is this:
public int SumOfShortestAndLenghtiestWord(string[] words) { if (words.Length == 0) throw new Exception("N/a to empty array."); var min = words[0].Length; var max = words[0].Length; for(var i = 1; i < words.Length; i++) { if (words[i].Length > max) max = words[i].Length; if (words[i].Length < min) min = words[i].Length; } return min + max; }
minandmaxwould be easier. And lines of code would be less. - Rootware