Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient C# SharePoint List iteration

I'm doing some custom code for a SharePoint webpart in C#. Specifically, I'm making a quiz, my main point here addressing the list that holds the question, answer choices, and correct answer.

At the last stage of the quiz I need to check the answers selected by the user against the correct answer in the list. Currently, I'm doing the following to check if each is correct, which I'm assuming isn't very efficient because it iterates through each question. Is there a method, specifically for the SPList foreach loop, that would be more efficient?

                // 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....
like image 347
Eric Di Bari Avatar asked Mar 08 '11 18:03

Eric Di Bari


3 Answers

If you need to access every item in the list, then using a foreach is perfectly ok:

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

Generally, most people need to work with a subset of items from a list. In this case, you'd most likely want to retrieve a subset of items from the list and then do your processing. For example, by using SPQuery and 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);

FYI... Here is a good link going over some other options: https://www.nothingbutsharepoint.com/sites/devwiki/SP2007Dev/Pages/Accessing%20list%20items%20using%20the%20object%20model.aspx

SharePoint has a lot of tools. It is always worth determining which tool is right for the job at hand. :)

like image 80
Kit Menke Avatar answered Oct 11 '22 16:10

Kit Menke


This may seem dumb but instead of using a class to store the variables why not use a simple array? Or an even easier way would be to write an sql query to compare the answer array to the answers stored in the database. Your solution seems to be way to much OO wizardry but maybe its just me.

Also look at answer Performance of Arrays vs. Lists

It looks like it would be faster to use a for loop than a foreach loop to iterate over a list.

like image 40
Zen Devel Avatar answered Oct 11 '22 17:10

Zen Devel


I would imagine using the SpList.GetItems with a correctly formatted query will give you the number of correct answers.

The U2U CAML Query Builder tool may be of use in getting a correct query.

like image 33
Nat Avatar answered Oct 11 '22 17:10

Nat