Оптимизация преобразования IEnumerable в HashSet в 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;
    }
}

Эта функция вызывается много раз, скажем, 1000 раз, и в результирующем наборе 5000 студентов. Как мне оптимизировать эту функцию... Я знаю, что преобразование из IEnumerableв HashSetвызывает много накладных расходов. ToHashSet— мой метод расширения. Эта функция заключается в том, чтобы замедлить и съесть много времени.

9
задан Erik Schierboom 8 June 2013 в 09:47
поделиться