Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize IEnumerable to HashSet conversion in LINQ

public HashSet<Student> GetStudents(int studentId)
{
    IEnumerable<Student> studentTypes = this.studentTypes .Where(x => (x.studentID== studentId));
    if (studentTypes .FirstOrDefault() != null)
    {

        //return new HashSet<Student>(studentTypes);
        return studentTypes.ToHashSet();
    }
    else
    {
        return new HashSet<Student>();
    }
}

public static class LinqUtilities
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable)
    {
        HashSet<T> hashSet = new HashSet<T>();

        foreach (var en in enumerable)
        {
            hashSet.Add(en);
        }

        return hashSet;
    }
}

This function is called alot of times say 1000 times and there are 5000 students in the result set. How can I optimize this function ...I know that the conversion from IEnumerable to HashSet is causing a lot of overheads. ToHashSet is my extension method. This function is to slow and eating a lot of time.

like image 720
abbas Avatar asked Jun 28 '12 13:06

abbas


1 Answers

First, you don't need to enumerate the hashset values in your utilities function you could improve the efficient by using nice static extension class written by @Jon

Converting linq result to hashset

and i think you don't need to check on the FirstOrDefault since the extension will handle the new student object given T so you could change to more clean and tidy way.

IEnumerable<Student> studentTypes = this.studentTypes.Where(x => (x.studentID== studentId));
return studentTypes.toHashSet();

The other option is you can pass you IEnumerable into your constructor for HashSet like

HashSet<Student> studentTypes = new HashSet<Student>(this.studentTypes.Where(x => (x.studentID== studentId)));

so you only have one line of code in your GetStudents function

like image 115
Turbot Avatar answered Oct 12 '22 01:10

Turbot