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

vrrathod picture vrrathod · Jun 29, 2011 · Viewed 31.2k times · Source

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?

Answer

Brandon Moretz picture Brandon Moretz · Jun 29, 2011

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