在LINQ中优化IEnumerable到HashSet转换

abb*_*bas 9 linq performance ienumerable hashset

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个函数被称为很多次,比如1000次,结果集中有5000个学生.我怎样才能优化这个功能...我知道从转换IEnumerableHashSet导致很多开销. ToHashSet是我的扩展方法.这个功能是减慢和吃很多时间.

Tur*_*bot 10

首先,您不需要在您的实用程序函数中枚举hashset值,您可以通过使用由@Jon编写的漂亮的静态扩展类来提高效率

将linq结果转换为hashset

我觉得你并不需要去检查FirstOrDefault由于延伸将处理给T上的新学生对象,所以你可以改变更整洁的方式.

IEnumerable<Student> studentTypes = this.studentTypes.Where(x => (x.studentID== studentId));
return studentTypes.toHashSet();
Run Code Online (Sandbox Code Playgroud)

另一个选择是你可以将IEnumerable传递给你的HashSet构造函数

HashSet<Student> studentTypes = new HashSet<Student>(this.studentTypes.Where(x => (x.studentID== studentId)));
Run Code Online (Sandbox Code Playgroud)

所以你的GetStudents函数中只有一行代码