I have an array of strings of variable length. Currently I have a loop that iterates through the array to find the longest string in array. Is there any way I could use LINQ to write it in more efficient and / or cleaner way?
I have an array of strings of variable length. Currently I have a loop that iterates through the array to find the longest string in array. Is there any way I could use LINQ to write it in more efficient and / or cleaner way?
Since .NET 6, you can use the MaxBy method. It's O(N) and straightforward:
var strings = new string[] { "1", "02", "003", "0004", "00005" };
string? longest = strings.MaxBy(s => s.Length); // longest == "00005"