gpt4 book ai didi

c# - 使用linq计算gridview中的特定特征

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:35 24 4
gpt4 key购买 nike

我想用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;
}

在表格中我有一个 GridView “gvData”:

gvData.DataSource = obj.TitForTat().Tables[0];

我的 gridview 有一列“prison1”,有时是“d”,有时是“c”。我需要使用 linq 计算这些迭代;

最佳答案

您可以使用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");

关于c# - 使用linq计算gridview中的特定特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20330906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com