user1022677
user1022677

Reputation: 715

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

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;
}

Upvotes: 55

Views: 48511

Answers (8)

Justas
Justas

Reputation: 159

The simplest way would be to use MaxBy, available since .Net6:

string longestString = list.MaxBy(x => x.Length);

Upvotes: 2

Sudharshan Kalale
Sudharshan Kalale

Reputation: 37

I thought there was a better way to get the longest string in a list of strings using the lambda expressions. One such way is as below.

string longestString = list.Max(arr => arr);

Hope this works good for the answer seekers.

Upvotes: 2

daniele3004
daniele3004

Reputation: 13910

To get the longest string in list of object/string try this:

List<String> list = new List<String>();
list.Add("HELLO");
list.Add("HELLO WORLD");
String maxString = list.OrderByDescending(x => x.Length).First();

The variable maxString will contain the value "HELLO WORLD"

Upvotes: 1

Eric Lippert
Eric Lippert

Reputation: 660030

The method you want is typically called "MaxBy" and it is unfortunately not included in the standard set of sequence operators. Fortunately it is very easy to write yourself. See this answer for an implementation:

Linq group by with a sub query

Upvotes: 4

cordialgerm
cordialgerm

Reputation: 8503

Add a ThenBy() to guarantee a return order if there are multiple strings with the same length

var longest = list.OrderByDescending(s => s.Length)
                   .ThenBy(s => s)
                   .FirstOrDefault();

Upvotes: -1

amiry jd
amiry jd

Reputation: 27585

var list = new List<string>(); // or string[] or any

list.Add("a");
list.Add("ccc");
list.Add("bb");
list.Add("eeeee");
list.Add("dddd");

// max-length
var length = list.Max(s => s.Length);

// biggest one
var biggest = list.FirstOrDefault(s => s.Length == length);

// if there is more that one by equal length
var biggestList = list.Where(s => s.Length == length);

// by ordering list
var biggest = list.OrderByDescending(s => s.Length).FirstOrDefault();

// biggest-list by LINQ
var bigList2 = from s in list where s.Length == list.Max(a => a.Length) select s;

// biggest by LINQ
var biggest2 = bigList2.FirstOrDefault();

Upvotes: 11

SimonC
SimonC

Reputation: 6718

This will do it with only one loop iteration:

list.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);

Upvotes: 112

Daniel
Daniel

Reputation: 31579

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

Upvotes: 42

Related Questions