gpt4 book ai didi

c# - 最高效的 C# SharePoint 列表迭代

转载 作者:太空狗 更新时间:2023-10-29 23:18:26 26 4
gpt4 key购买 nike

我正在使用 C# 为 SharePoint webpart 编写一些自定义代码。具体来说,我正在做一个测验,我的主要观点是解决包含问题、答案选择和正确答案的列表。

在测验的最后阶段,我需要将用户选择的答案与列表中的正确答案进行比较。目前,我正在执行以下操作来检查每个问题是否正确,我认为这不是很有效,因为它会遍历每个问题。有没有专门针对 SPList foreach 循环的方法更有效?

                // 1. Store questions and answers in class
List<submittedAnswers> answeredQuestions = new List<submittedAnswers>();

// 2. From POST pull answered question IDs and answer IDs (which correspond to the question primary key and answer choice number both stored in the list)
// INSERT BEAUTFIUL AND EFFICIENT WHILE LOOP HERE

// 3. Loop through each question is list, if question was given, test if correct/incorrect
using (SPWeb myWeb = mySite.OpenWeb())
{
SPList answerList = myWeb.Lists[questionList];
foreach (SPListItem quizEntry in answerList.Items)
{
int pullAnswerId = int.Parse(quizEntry["Answer"].ToString()); // Pull answer number from list
int pullQuestionId = int.Parse(quizEntry["ID"].ToString()); // Pull primary key of question

submittedAnswers result = answeredQuestions.Find(delegate(submittedAnswers e) { return e.questionId == int.Parse(quizEntry["ID"].ToString()); });
if (result != null)
{
if (result.responseId != pullAnswerId) // If the response was different from the answer
incorrectAnswers++;
else
correctAnswers++;
}
}
}
// C# quiz grading magic here....

最佳答案

如果您需要访问列表中的每一项,那么使用 foreach 是完全可以的:

SPList answerList = myWeb.Lists[questionList];
foreach (SPListItem quizEntry in answerList.Items)
{
// todo...
}

通常,大多数人需要处理列表中的项目子集。在这种情况下,您很可能希望从列表中检索项目的子集,然后进行处理。例如,通过使用 SPQuery 和 SPList.GetItems ( code from the full example here ):

// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='Status'/>",
"<Value Type='CHOICE'>Not Started</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");

query.ViewFields = string.Concat(
"<FieldRef Name='AssignedTo' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");

query.ViewFieldsOnly = true; // Fetch only the data that we need.

// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);

仅供引用...这是一个很好的链接,可以查看其他一些选项:https://www.nothingbutsharepoint.com/sites/devwiki/SP2007Dev/Pages/Accessing%20list%20items%20using%20the%20object%20model.aspx

SharePoint 有很多工具。始终值得确定哪种工具适合手头的工作。 :)

关于c# - 最高效的 C# SharePoint 列表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5236786/

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