我和几个学生一起保存了这样的Viewstates:
ViewState[currentStudent] = currentGradesList;
但是现在我需要让所有观察者获得所有成绩的平均值,我已经学会了用这样的字符串来做到这一点:
foreach (string str in ViewState.Keys) {....}
并且有效。
但现在我尝试
foreach(List<double> grades in ViewState.Keys) {....}
&#34;成绩&#34;保持为空,我收到错误:
Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.Double]'.
我想它说Keys是字符串,但我怎么会得到所有列表?
答案 0 :(得分:3)
您循环遍历foreach
循环中的键名,而不是实际值。您可以使用foreach循环变量的值(现在是ViewState字典中的键的名称)从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
}
答案 1 :(得分:1)
foreach (string str in ViewState.Keys)
{
var grades = ViewState[str] as List<double>;
if(grades != null)
{
var average = grades.Average();
}
}
答案 2 :(得分:0)
解决方案: 我循环遍历视图状态键的名称,而不是值。所以现在我把它改成了
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();`