Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 513
vrrathod Avatar asked Jun 29 '11 16:06

vrrathod


People also ask

How do you find the longest string in an array C++?

I wrote this code: char a[100][100] = {"solol","a","1234567","123","1234"}; int max = -1; for(int i=0;i<5;i++) if(max<strlen(a[i])) max=strlen(a[i]); cout<<max; The output it gives is -1. But when I initialize the value of max by 0 instead of 1, the code works fine.

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 find the longest string in a string python?

Python Max Length of String in List. To find the maximum length of a string in a given list, you can use the max(lst, key=len) function to obtain the string with the maximum length and then pass this max string into the len() function to obtain the number of characters of the max string.


1 Answers

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

like image 121
Brandon Moretz Avatar answered Oct 27 '22 02:10

Brandon Moretz