Darf Zon
Darf Zon

Reputation: 6378

How to improve this LINQ TO SQL queryable?

I've got a Student list where I would like to create a query where gets all the items and not 1 by 1 as I show the code below:

            IEnumerable<Student> = ...
            List<AnsweredTest> ats = new List<AnsweredTest>();

            foreach (var s in students)
            {
                query = from at in Database.Current.AnsweredTests
                        where at.StudentId == s.StudentId
                        select at;

                ats.Add(query.Single());
            }

            listView.ItemsSource = ats;

This is not good for the performance. I hope make myself clear, if not please let me know.

Upvotes: 0

Views: 115

Answers (3)

Johan Lindqvist
Johan Lindqvist

Reputation: 56

Maybe something like this:

var studentIds = students.Select(s => s.StudentId);
var ats = Database.Current.AnsweredTests.Where(at => studentIds.Contains(at.StudentId));

Upvotes: 0

jessehouwing
jessehouwing

Reputation: 114641

Either do a Join:

   query = from at in Database.Current.AnsweredTests 
    join s in Database.Current.Students on at.StudentId == s.StudentId
    where s... // filter s if needed.
    select at;

Or grab the list of student id's and pass it into the query:

   int[] studentIds = students.Select(s => s.StudentId).ToArray();
   query = from at in Database.Current.AnsweredTests
     where studentIds.Any(id => at.StudentId == id)
     select at;

Upvotes: 1

lante
lante

Reputation: 7336

var ats = Database.Current.AnsweredTests
    .Where(at => students.Any(s => s.StudentId == at.StudentId).ToList()

Upvotes: 1

Related Questions