Conkbabes
Conkbabes

Reputation: 17

C# For Each Loop, using database entity

I have a database called db1104983, I'm using entity framework 6. My database is made up of one table called Student. So all my entries in my DB are Students.

I'm trying to create a function that will calculate the amount of people in a class that passed.

The DB already has a field FinalGrade which holds the final grade for each student. It is considered a pass if it is grade A-D

I originally had the following

int classSize = context.Students.Count();                   
int FinalPercentage = passedStudents / classSize * 100;                  
MessageBox.Show(+FinalPercentage + "% of the class have passed!");

Then just before i add my new student object to the DB I had this code

               if (s1.FinalGrade == "A")
                {
                    PassedStudents++;
                }

                else if (s1.FinalGrade == "B")
                {
                    PassedStudents++;
                }
                else if(s1.FinalGrade =="C")
                {
                    PassedStudents++;

                }
                else if (s1.FinalGrade == "D")
                    PassedStudents++;
                else
                {
                    //do nothing
                }

However it seems to dispose of the passed students variable before i can use it, so i am trying to do the following

private void displayPercentage(object s1, int passedStudents)
    {
        using (db1104983Entities1 context = new db1104983Entities1())
        {
    foreach(Student in context) 
    if( s1.FinalGrade== "A" || s1.Finalgrade == B || s1.Finalgrade == C  

|| s1.FinalGrade == D)
    {
        passedStudents++
    } 
    else {

        //do nothing
             }
        }
    }

but It is giving me all sorts of errors so I'm unsure if this is correct way of doing it. Any help would be much appreciated.

Thanks.

        }









    }
}

Upvotes: 0

Views: 630

Answers (1)

juharr
juharr

Reputation: 32296

Seems like you can get this information from one DB query

var results = (from student in context.Students
               group student by 1 into grp
               select new
               {
                   ClassSize = grp.Count(),
                   PassingStudents = grp.Count(s => s.FinalGrade != "F")
               }).Single();
var passingPercent = 100.0 * (double)results.PassingStudents / (double)results.ClassSize;

This assumes that "F" reprensts all non-passing students. If you have students will a null grade or something else you can substitute that with s.FinalGrade == "A" || s.FinalGrade == "B" || s.FinalGrade == "C" || s.FinalGrade == "D".

Upvotes: 1

Related Questions