I have the following lines in my code. They are taking more place than they should. Any suggestions for a smaller code.
string longestString;
string shortestString;
if (string1.Length > string2.Length)
{
longestString = string1;
shortestString = string2;
}
else
{
longestString = string2;
shortestString = string1;
}
I know, not a really important question, but this is taking 2/3 of the entire method and not the important stuff.
Perhaps:
int diff = string1.Length.CompareTo(string2.Length);
string longestString = diff > 0 ? string1 : string2;
string shortestString = diff > 0 ? string2 : string1;
But if you have more than these two strings and you want a general solution you could use:
var lenLookup = new[] { string1, string2 }.OrderBy(s => s.Length).ToList();
string shortestString = lenLookup.First();
string longestString = lenLookup.Last();
Since your code would always perform either the if or else path, pick one as "default" and merge it with variable declaration:
string longestString = string2
string shortestString = string1;
if (string1.Length > string2.Length)
{
longestString = string1;
shortestString = string2;
}
Bonus points for the fact that you'll actually initialize those variables.
Well, you could do this to clear your method up;
public string GetLongestString(string str1, string str2)
{
return str1.Length > str2.Length ? str1 : str2;
}
public string GetShortestString(string str1, string str2)
{
return str1.Length > str2.Length ? str2 : str1;
}
string longestString = GetLongestString(string1, string2);
string shortestString = GetShortestString(string1, string2);
And reuse it whenever you want!
Heck, make it even cooler (in co-op mode with Tim);
public IEnumerable<string> GetLongestStrings(params string[] strings)
{
//returns first string with largest length out of given argumenst
int maxSize = strings.Max(str => str.Length);
return strings.Where(s => s.Length == maxSize);
}
public IEnumerable<string> GetShortestStrings(params string[] strings)
{
//returns first string with shortest length out of given arguments
int minSize = strings.Min(str => str.Length);
return strings.Where(s => s.Length == minSize);
}
Usage;
string longestString = GetLongestStrings("str1", "str2", /*...*/ "strN").FirstOrDefault();
EDIT1: My first implementation is not the most efficient. As Tim suggested;
public string GetLongestString(params string[] strings)
{
return strings.OrderBy(s => s.Length).First();
}
public string GetShortestString(params string[] strings)
{
return strings.OrderByDescending(s => s.Length).First();
}
Usage;
string longestString = GetLongestString("str1", "str2", /*...*/ "strN");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With