如何检索所有视图状态列表
How to retrieve all viewstate lists
我正在和几个学生一起保存 Viewstates:
ViewState[currentStudent] = currentGradesList;
但现在我需要获取所有视图状态以获得所有成绩的平均值,我已经学会了用这样的字符串来做到这一点:
foreach (string str in ViewState.Keys) {....}
行得通。
但现在当我尝试
foreach(List<double> grades in ViewState.Keys) {....}
"grades" 保持为空,我得到错误:
Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.Double]'.
我猜它说键是字符串,但是我怎么才能得到所有列表呢??
您正在遍历 foreach
循环中键的名称,而不是实际值。您使用 foreach 循环变量的值(现在是 ViewState 字典中的键的名称)从视图状态中获取值。
将您的 foreach 循环更改为类似这样的内容
foreach(var key in ViewState.keys)[
var grades = ViewState[key] as List<double>;
//LINQ has built in Average and Sum abilities on lists
//I don't know what a CurrentStudentGrades looks like
//but here is an example of using the built in average
var studentAverage = grades.Average(x=>x.Grade);
//do whatever else you are wanting to do
}
foreach (string str in ViewState.Keys)
{
var grades = ViewState[str] as List<double>;
if(grades != null)
{
var average = grades.Average();
}
}
解决方法:
我正在遍历视图状态键的名称,而不是值。所以现在我把它改成了
Foreach (string str in ViewState.Keys)
{ //And then the value of "str"...
List<double> templist = (List<double>)ViewState[str];
然后是我的代码的其余部分,这并不重要,但这里是为了获得每个学生的平均成绩,以及所有学生的平均成绩
foreach (double grade in templist)
{
currenttotal += grade;
}
currentaverage = currenttotal / templist.count;
AllAveragesList.add(currentaverage)
foreach (double average in AllAveragesList)
{
totalOfAll += average
}
averageOfAll = totalOfAll / AllAveragesList.count();`
我正在和几个学生一起保存 Viewstates:
ViewState[currentStudent] = currentGradesList;
但现在我需要获取所有视图状态以获得所有成绩的平均值,我已经学会了用这样的字符串来做到这一点:
foreach (string str in ViewState.Keys) {....}
行得通。
但现在当我尝试
foreach(List<double> grades in ViewState.Keys) {....}
"grades" 保持为空,我得到错误:
Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.Double]'.
我猜它说键是字符串,但是我怎么才能得到所有列表呢??
您正在遍历 foreach
循环中键的名称,而不是实际值。您使用 foreach 循环变量的值(现在是 ViewState 字典中的键的名称)从视图状态中获取值。
将您的 foreach 循环更改为类似这样的内容
foreach(var key in ViewState.keys)[
var grades = ViewState[key] as List<double>;
//LINQ has built in Average and Sum abilities on lists
//I don't know what a CurrentStudentGrades looks like
//but here is an example of using the built in average
var studentAverage = grades.Average(x=>x.Grade);
//do whatever else you are wanting to do
}
foreach (string str in ViewState.Keys)
{
var grades = ViewState[str] as List<double>;
if(grades != null)
{
var average = grades.Average();
}
}
解决方法: 我正在遍历视图状态键的名称,而不是值。所以现在我把它改成了
Foreach (string str in ViewState.Keys)
{ //And then the value of "str"...
List<double> templist = (List<double>)ViewState[str];
然后是我的代码的其余部分,这并不重要,但这里是为了获得每个学生的平均成绩,以及所有学生的平均成绩
foreach (double grade in templist)
{
currenttotal += grade;
}
currentaverage = currenttotal / templist.count;
AllAveragesList.add(currentaverage)
foreach (double average in AllAveragesList)
{
totalOfAll += average
}
averageOfAll = totalOfAll / AllAveragesList.count();`