How return max value in LINQ, please?

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
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top