我正在尝试根据SharePoint列表数据(问题和4个答案选项)创建一个测验窗口小部件。 我能够找到一种方法来拉出10个随机行并阅读问题和答案。 但是,我似乎无法想出的是用随机顺序填充RadioButton列表以及答案选项(针对该特定行项目)的逻辑。 这是我到目前为止的代码:请建议可能的策略/代码
//Function to pull 10 random questions from the "QuestionsAndAnswers" list for the correspoding LessonPlan
public void LoadQuestions()
{
try
{
SPWeb thisWeb = SPContext.Current.Web;
//Accessing the list correspoding to the current LessonPLan subsute
SPList oSPList = thisWeb.Lists["QuestionsAndAnswers"];
//Using a query in case there is a need tofilter by LessonID
SPQuery oSPQuery = new SPQuery();
oSPQuery.RowLimit = 10;
SPListItemCollection oSPListItemCollection = oSPList.GetItems(oSPQuery);
Random rand = new Random();
List <int> tempStore = new List<int>();
List <int> tempStore2 = new List<int>();
int tempValue = 0;
//int tempValue2 = 0;
int icount = 0;
int iMax = oSPListItemCollection.Count;
//int icount2 = 0;
//int iMax2 = oSPListItemCollection.Count;
SPListItem thisItem;
Label thisQuestion;
Label thisCorrectAnswer;
RadioButtonList thisAnswers;
while (icount < 10)
{
tempValue = rand.Next(1, iMax);
if (tempStore.Exists(value => value == tempValue))
continue;
else
{
tempStore.Add(tempValue);
thisQuestion = (Label) UpdatePanelMaster.FindControl("Question" + icount.ToString());
thisItem = oSPListItemCollection[tempValue];
thisQuestion.Text= thisItem["Question"].ToString();
//Inside loop to handle random answer arrangements
thisAnswers = (RadioButtonList) UpdatePanelMaster.FindControl("RadioButtonList" + icount.ToString());
//The following 4 lines of code populates the RadioButton List only in order on every row item run
//How to randomize the order?
thisAnswers.Items.Add(thisItem["CorrectAnswer"].ToString();
thisAnswers.Items.Add(thisItem["IncorrectAnswer1"].ToString();
thisAnswers.Items.Add(thisItem["IncorrectAnswer2"].ToString();
thisAnswers.Items.Add(thisItem["IncorrectAnswer3"].ToString();
thisCorrectAnswer = (Label) UpdatePanelMaster.FindControl("CorrectAnswer" + icount.ToString());
thisCorrectAnswer.Text= thisItem["CorrectAnswer"].ToString();
}
tempValue = 0;
icount++;
}
}
//End random question handling
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:1)
尝试使用LINQ:
// start with an array of the question key strings
new[] { "CorrectAnswer", "IncorrectAnswer1", "IncorrectAnswer2", "IncorrectAnswer3" }
// for each key string s, select the relevant answer string
.Select(s => thisItem[s].ToString())
// sort by a random number (i. e. shuffle)
.OrderBy(s => rand.Next())
// convert to a List<T> (for the ForEach method)
.ToList()
// for each answer string s in the list, add s to thisAnswers.Items
.ForEach(s => thisAnswers.Items.Add(s));