问题
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?
回答1:
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
回答2:
strings.Aggregate(string.Empty, (seed, f) => f.Length > 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.
回答3:
string [] strings;
return strings.OrderByDescending (s => s.Length).First ();
回答4:
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.
回答5:
Even though this is an old question I'd like to add that the most efficient answer is not provided. It isn't a one liner, but it's the fastest and returns a collection of the longest strings, which OrderBy or Aggregate doesn't provide. Matt Ellen was the closest with his answer, but using Max within his Where makes it rather slow when you're working with a large collection.
The correct answer should be:
int maxLength = collection.Max(x => x.Length);
string[] longestStrings = collection.Where(x => x.Length == maxLength).ToArray();
Consider using the ?. (in C# 6.0) and ?? operators to check for null values if your collection can contain these.
回答6:
I don't have a compiler right now but this will also work.
string[] arr = new string[] { "a", "aa", "aaa" };
var longest = arr.Max(w => w.Length)
来源:https://stackoverflow.com/questions/6524407/how-to-find-the-longest-string-in-a-string-using-linq