What is the best way to get the object, within a list of that object type, that has the highest ID number?

I've been trying to figure it out and I can manage to get the highest ID number but not the object containing that ID number.

Any help would be massivly appreciated,


Recommended Answers

All 7 Replies

class Custom
    public int EmployeeId { get; set; }
    public int Index { get; set; }

List<Custom> data = new List<Custom>()
    new Custom() { EmployeeId = 1, Index = 1 },
    new Custom() { EmployeeId = 1, Index = 2 },
    new Custom() { EmployeeId = 1, Index = 3 },
    new Custom() { EmployeeId = 2, Index = 3 },
    new Custom() { EmployeeId = 2, Index = 2 },
    new Custom() { EmployeeId = 2, Index = 1 },
    new Custom() { EmployeeId = 3, Index = 8 }

Custom item = data.Aggregate((a, x) => (x.Index > a.Index) ? x : a);
commented: Exactly what I was after. +7

Spot on @pritaeas that's worked a treat.

Linq is new teratory for me.

Thanks again.

Just yesterday that I had to explain something like this to a coworker ;) I keep such snippets in Linqpad. If you don't know it, check it out.

I've just had a little look and I'll be acquiring myself a copy of that!

Thanks again.

You could use

Custom item = data.OrderByDescending(obj => obj.Index).FirstOrDefault();

Does the same thing but looks tidier :)

That's what you get when copying snippets made to solve other problems, then stripping them ;)

Aggregate is incredibly useful. As an explanation to Chris, Aggregate takes the result of the function and passes it as the parameter into the next iteration of the function. This makes it possible to create an aggregate of data from your list (hence the function name) :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.