Patrik18
Patrik18

Reputation: 329

How to avg() in linq

I'm trying write my sql commang to Linq:

SQL:

select avg(sub.evaluation) from submit_task sub where student_id='" + idStudent + "' and state='close';

Linq:

double avg = (ado.submit_task.Where(r => (r.id == idStudent && r.state == "close")).Average(r => r.evaluation));

avgStudent = avg.ToString();

but this is not working, when I delete && r.state == "close" statement, I got result, but it's incorrect.

thank you.

Upvotes: 1

Views: 1023

Answers (2)

Patrik18
Patrik18

Reputation: 329

ok, here's code, which working:

var avgEvalClose = (from sub in ado.submit_task
                    where sub.student_id.Equals(idStudent)
                    where sub.state.Equals("close")
                    select sub.evaluation).Average();
avgStudent = avgEvalClose.ToString();

Upvotes: 0

Saravanan
Saravanan

Reputation: 7854

I have tried the same with a sample set of data and it works fine

 List<student> students = new List<student>
        {
            new student{id="1",state="close",evaluation=5},
            new student{id="1",state="close",evaluation=4}
        };
        double avg = (students.Where(r => (r.id == "1" && r.state == "close")).Average(r => r.evaluation));

public class student
{
    public string id { get; set; }
    public string state { get; set; }
    public int evaluation { get; set; }
}

may be you should check the data in the db or modify the state="close" part of the query

Upvotes: 3

Related Questions