我想使用linq计算gridview中“d”的数量
我的数据集是这样的:
public DataSet TitForTat()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("myt");
dt.Columns.Add(new DataColumn("iteration", typeof(int)));
dt.Columns.Add(new DataColumn("prison1", typeof(string)));
dt.Columns.Add(new DataColumn("prison2", typeof (string)));
prison[] prisons = new prison[2];
prisons[0] = new prison();
prisons[1] = new prison();
//---------------------------
DataRow dr = dt.NewRow();
prisons[0]._state = "c";
prisons[1]._state = valueOfState[rd.Next(0, 1)];
dr["iteration"] = 0;
dr["prison1"] = "c";
dr["prison2"] = prisons[1]._state;
dt.Rows.Add(dr);
//----------------------
for (int i = 1; i <= _iteration; i++)
{
prisons[0]._state = prisons[1]._state;
prisons[1]._state = valueOfState[rd.Next(0, 2)];
DataRow dr1 = dt.NewRow();
dr1["iteration"] =i;
dr1["prison1"] = prisons[0]._state;
dr1["prison2"] = prisons[1]._state;
dt.Rows.Add(dr1);
}
ds.Tables.Add(dt);
return ds;
}
在表格中我有一个网格视图“gvData”:
gvData.DataSource = obj.TitForTat().Tables[0];
我的gridview有一个列“prison1”,有时是“d”,有时是“c”。 我需要使用linq计算这些迭代;
答案 0 :(得分:0)
您可以使用GroupBy
:
var prisonGroups = ((DataTable)gvData.DataSource).AsEnumerable()
.GroupBy(row => row.Field<string>("prison1"));
int countC = prisonGroups
.Where(g => g.Key == "c")
.Sum(g => g.Count());
int countD = prisonGroups
.Where(g => g.Key == "d")
.Sum(g => g.Count());
这是另一种方法:
DataTable source = (DataTable)gvData.DataSource;
int cPrisoners = source.AsEnumerable()
.Count(row => row.Field<string>("prison1") == "c");
int dPrisoners = source.AsEnumerable()
.Count(row => row.Field<string>("prison1") == "d");