How return max value in LINQ, please?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
R

Ronald S. Cook

I have the following values in my AnimalTag table under the column
AnimalTagNumber.

123456
234567
345678
D00001
D00002
D00003

In LINQ, How can I select the Max (although it is not numeric) where the
first character is "D"?

I.e. for the above I'm wanting to return D00003.

Thanks for any assistance,
Ron
 
Ronald S. Cook said:
I have the following values in my AnimalTag table under the column
AnimalTagNumber.

123456
234567
345678
D00001
D00002
D00003

In LINQ, How can I select the Max (although it is not numeric) where the
first character is "D"?

I.e. for the above I'm wanting to return D00003.

You'll have to define exactly what you mean by "max" - lexicographic?

If you're happy with the behaviour of string in terms of
IComparable<string>, you can just call Max:

using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
var words = new[]
{
"123456",
"234567",
"345678",
"D00001",
"D00002",
"D00003"
};

var max = words.Where(w => w[0]=='D')
.Max();

Console.WriteLine(max);
}
}

I'm somewhat surprised that you can't specify an IComparer<string> to
be honest - although it would be easy to write that as an extra
extension method.
 
Back
Top