简体   繁体   English

使用linq从网格中的列中获得不同的值

[英]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. 好的..我仍然不确定为什么不重复查询DataSource就要做,但是这是一种可能会指出正确方向的方法。 gv1 is the ID of your GridView , and for demonstration purposes I'll use the first column: gv1是GridView的ID,出于演示目的,我将使用第一列:

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. UPDATE刚看到这似乎无法将Linq与ASP.Net导航菜单结合使用(由Jon Skeet回答),并认为它可能适用于此处的问题。

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,您需要通过显式指定该项,将其Cast为IEnumerable(因为我愿意打赌GridViewRowsCollection没有实现IEnumerable)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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