Search code examples
c#linq-to-objects

how to find the longest string in a string[] using LINQ


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?


Solution

  • It won't be much more efficient, however it would be a bit cleaner to do something like:

    var strings = new string[] { "1", "02", "003", "0004", "00005" };
    
    string longest = strings.OrderByDescending( s => s.Length ).First();
    

    Output: 00005