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

前端 未结 7 504
灰色年华
灰色年华 2020-12-07 20:27

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

static string GetLongestStringInList()
{
    string long         


        
相关标签:
7条回答
  • 2020-12-07 21:03
    var list = new List<string>(); // or string[] or any
    
    list.Add("a");
    list.Add("ccc");
    list.Add("bb");
    list.Add("eeeee");
    list.Add("ffffdd");
    
    // 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();
    
    0 讨论(0)
  • 2020-12-07 21:04

    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"

    0 讨论(0)
  • 2020-12-07 21:16

    This will do it with only one loop iteration:

    list.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);
    
    0 讨论(0)
  • 2020-12-07 21:17

    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

    0 讨论(0)
  • 2020-12-07 21:24

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

    0 讨论(0)
  • 2020-12-07 21:24

    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();
    
    0 讨论(0)
提交回复
热议问题