0

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,

Thanks.

3
Contributors
7
Replies
22
Views
2 Years
Discussion Span
Last Post by Ketsuekiame
1
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);
Votes + Comments
Exactly what I was after.
0

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.

1

You could use

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

Does the same thing but looks tidier :)

1

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) :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.