Get max DataGridViewRow based on Record ID using LINQ

374 Views Asked by At

I am trying to get the DataGridViewRow with the max record id value. I am able to get the record id itself but I need to find the row itself.

This is my code for getting the max record id and it works fine:

var addedRow =
                dataGridView.Rows
                .Cast<DataGridViewRow>()
                .Where(r => r.Cells[Glossary.RowType].Value.ToString().Equals(Glossary.RowTypeCustom))
                .Select(r => Convert.ToInt(r.Cells[Glossary.RecordId].Value))
                .Max();

I tried:

.Max(r => r.Cells[Glossary.RecordId].Value);

I am not clear how to the get the row itself so I can give focus to it:

dataGridView.CurrentCell = addedRow;
1

There are 1 best solutions below

2
On BEST ANSWER

try using this.

    var addedRow =
            dataGridView.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells[Glossary.RowType].Value.ToString().Equals(Glossary.RowTypeCustom))
            .OrderByDescending(r => Convert.ToInt(r.Cells[Glossary.RecordId].Value))
            .FirstOrDefault();

hope it will help.