I have a List<>
which contains several strings. For example {a1, a2, a15, a3, a16, a1}
. I want to get the string with the Max number (a16). I tried using Where() and Max() but then it will return the maximum value (16), where I want to return the string (a16).
I guess I could do it with an additional Where()
and contains()
but I was wondering if I could do it in a simpler way.
Here is the code example:
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