How to get the key when using the linq Max () method

I have List<>one that contains several lines. For example {a1, a2, a15, a3, a16, a1}. I want to get the string with the maximum number (a16). I tried using Where () and Max (), but then will return the maximum value (16), where I want to return the string (a16). I think I could do it with extra Where()and contains(), but I was wondering if I could do it in a simpler way.

Here is a sample code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace linq_example
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string> {"b1", "a1", "a2","a9", "a16", "a1", "a5" , "b20"};
            var max = list.Where(i => i.IndexOf("a") != -1).Max(a => Convert.ToInt32(a.Substring(1)));
            Console.WriteLine(max.ToString());
            Console.ReadLine();
        }
    }
}

This program will print 16, where I wanted to print a16

+4
source share
3 answers
var biggest = list.OrderByDescending(x => Convert.ToInt32(a.Substring(1)).First();

, LINQ OrderBy "". . Max(). LINQ.

: LINQ: .Max()

MoreLINQ MaxBy(), .

+2

:

:

using System.Linq;
using System.Text.RegularExpressions; 

regex, int, :

var max = list.Max(x => int.Parse(Regex.Match(x, @"\d+")));
+1

List<string> list = new List<string> { "a1", "a2", "a15", "a3", "a16", "a1" };
var largest = list.OrderBy(s => int.Parse(Regex.Match(s, @"\d+").ToString())).Last();
0

All Articles