-2

Could anyone tell me please what the best/most efficient way is to get the index of the row in a datagrid view that has the smallest integer value for a particular column.

I did this using a foreach loop to traverse the collection of rows and compare the respective value of each row and store the smallest. Each time I find a smaller value I update my "smallest" variable with that value. This works but I'm pretty sure there must be some lambda expression that does a better job. Could anyone help please?

This is the column containing the value:

dgvItems.Rows[i].Cells["col1"].Value

Many thanks.

user2430797
  • 320
  • 5
  • 18

2 Answers2

1

the best way to do so is with LINQ queries,

LINQ is better looking, more readable and more efficient than for loops

you should use the DataGridView data source and not directly to the DataGridView data

DataTable dt = dgv.DataSource as DataTable;

MinRow:     var result = dt.Rows.IndexOf(dt.AsEnumerable().OrderBy(x => x["col1"]).First());
MaxRow:     var result1 = dt.Rows.IndexOf(dt.AsEnumerable().OrderByDescending(x => x["col1"]).First());

hope this could help you

Dor Lugasi-Gal
  • 1,430
  • 13
  • 35
0

I will help you for this one since you are not asking about using LINQ. Lets do it the "usual" way..

First, declare a new List

List<int> columnValue = new List<int>();

we will Iterate through each row in the grid

    foreach (DataGridViewRow row in myDataGrid.Rows)
    {
        if (null != row && null != row.Cells["col1"].Value)
        {
            //Add the value of columnValue to list
            columnValue.Add(Convert.ToInt32(row.Cells[0].Value.ToString()));
        }
    }

and get the MIN. value from LIST

    int result = columnValue.Min();

finally, get the index of the value we got from the LIST

    int i = columnValue.IndexOf(result); //returns the Index from "result" var
  • Thanks Louie, I appreciate the effort. However, this solution is computationally more intensive than what I currently have (as described in my OP) as it makes use of an additional collection plus the use of it's inherent Min method. But thanks anyway :-) – user2430797 Oct 30 '18 at 03:51