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

strings.Aggregate(string.Empty, (seed, f) => f?.Length ?? 0 > seed.Length ? f : seed);

Aggregate syntax is slightly harder to read than the other methods, but strictly speaking it's more efficient than the other approaches I see here as it doesn't require sorting. Just an O(N) implementation.

EDIT: This approach, along with most of the others here assumes there are no null values in your list, lest f.Length throw a null ref exception. A quick ternary operator (f != null ? f.Length : 0) would fix that if it were a valid for your enumerable.

EDIT (2.5 years later): Null coalesce is better than ternary null check.


string[] arr = new string[] { "a", "aa", "aaa" };

var longest = arr.Where(s => s.Length == arr.Max(m => m.Length)).First();

output aaa

This way the code is clearly getting you the string with the max length.


string [] strings;
return strings.OrderByDescending (s => s.Length).First ();

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