Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a LINQ function for getting the longest string in a list of strings?

Tags:

string

c#

linq

Is there a LINQ function for this is or would one have to code it themselves like this:

static string GetLongestStringInList() {     string longest = list[0];      foreach (string s in list)     {         if (s.Length > longest.Length)         {             longest = s;         }     }      return longest; } 
like image 541
user1022677 Avatar asked Nov 02 '11 04:11

user1022677


People also ask

How do you find the largest string in a list?

In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.

How do you return the longest string in a list?

Use Python's built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.


2 Answers

This will do it with only one loop iteration:

list.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur); 
like image 171
SimonC Avatar answered Oct 15 '22 10:10

SimonC


You can use this: list.OrderByDescending(s => s.Length).First();

like image 34
Dani Avatar answered Oct 15 '22 11:10

Dani