简体   繁体   中英

distinct value from a column in a grid using linq

I am using the below query to find the the distinct value count from a dataset column. How to find similarly to a grid column.

var distinctRows = (from DataRow dRow in _ds.Tables[0].Rows
                    select dRow["colName"]).Distinct();

Ok..I'm still not sure why you want to do it without requerying the DataSource, but here's one way that might point you in the right direction. gv1 is the ID of your GridView , and for demonstration purposes I'll use the first column:

string[] rowValues = new string[gv1.Rows.Count];

for (int i = 0; i < gv1.Rows.Count; i++)
{
    rowValues[i] = gv1.Rows[i].Cells[0].Text;
}

var distinctRows = (from r in rowValues
                    select r).Distinct();

This of course assumes that it's one cell per column, which may be a false (or at least bad) assumption.

UPDATE Just saw this Can't seem to use Linq with ASP.Net Navigation menu answered by Jon Skeet, and think it might apply to the issue here.

var distinctRows = (from GridViewRow r in gv1.Rows
                    select r.Cells[0].Text).Distinct();

Courtesy of Jon's answer, to use LINQ in this case you need to Cast to IEnumerable (as I'm willing to bet the GridViewRowsCollection doesn't implement IEnumerable) by explicitly specifying the item, as above.

您的网格可能已绑定到数据源,在这种情况下,对数据源使用linq查询比使用网格本身更有意义

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM