Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a List of distinct values from DataGridView

Tags:

c#

As the topic says: Is there a way to return a list of distinct values from a certain Column of a DataGridView?

like image 638
josef_skywalker Avatar asked Sep 18 '25 08:09

josef_skywalker


1 Answers

This should do what you asked for:

var vv = dataGridView1.Rows.Cast<DataGridViewRow>()
                           .Select(x => x.Cells[yourColumn].Value.ToString())
                           .Distinct()
                           .ToList();

Note that the simple version above assumes that there are only valid values. If you also may have new rows or empty cells you may want to expanded it like this:

var vv = dataGridView1.Rows.Cast<DataGridViewRow>()
                           .Where(x => !x.IsNewRow)                   // either..
                           .Where(x => x.Cells[column].Value != null) //..or or both
                           .Select(x => x.Cells[column].Value.ToString())
                           .Distinct()
                           .ToList();
like image 164
TaW Avatar answered Sep 20 '25 21:09

TaW