I have following linq query in my C# code , which is causing System.OutOfmemory excpetion
public SortedSet<string> GetstudentCount()
{
var studentCount= studentRepository
.GetBy(i => i.IsStudentEnabled && i.IsEnrolledAllSubjects)
.AsQueryable()
.AsNoTracking()
.ToList();
var studentSortedSet= new SortedSet<string>();
foreach (var student in studentCount)
{
var id = string.Format("{0}:{1}", student.studentFirstName, student.totalScore);
studentSortedSet.Add(id);
}
return new SortedSet<string>(studentCount);
}
So i am trying to optimize it and could see these options, but I am quite not sure since in my development database i don't have enough data to test. I am new to Entity Framework and to Linq, its a bit confusing to me to figure out which way is correct.
1) Removed ToList()
in Linq query, but foreach()
is taking same time as before(still slow)
2) Tried to remove entire foreach()
and added Select()
in the Linq query itself, like:
public SortedSet<string> GetStudentCount()
{
var studentCount= studentRepository
.GetBy(i => i.IsStudentEnabled &&
i.IsEnrolledAllSubjects)
.Select(string.Format("{0}:{1}",
student.studentFirstName, student.totalScore))
.AsQueryable()
.AsNoTracking()
.ToList();
return new SortedSet<string>(studentCount);
}
But even this takes same time(still slow)
I further thought of removing ToList()
here, but this method is used at many places( can confirm that no looping is done on studentCount
) , which i am quite not sure if this may cause more issues.
Any suggestion/advice on this is more appreciable.
EDIT2:
public IEnumerable<T> GetBy(Expression<Func<T, bool>> predicate)
{
return dbSet.Where(predicate);
}
EDIT:
It may be a basic question to many, I request them not to down vote this Question, as here I am trying to get some pointers on how to optimize. There are no hard feelings here. I am trying to learn the stuff and I would appreciate if this makes sense.Thank you