title: Optimize IEnumerable to HashSet conversion in LINQ
body: <pre><code>public HashSet&lt;Student&gt; GetStudents(int studentId)
  {
      IEnumerable&lt;Student&gt; studentTypes = this.studentTypes .Where(x =&gt; (x.studentID== studentId));
      if (studentTypes .FirstOrDefault() != null)
      {
  
          //return new HashSet&lt;Student&gt;(studentTypes);
          return studentTypes.ToHashSet();
      }
      else
      {
          return new HashSet&lt;Student&gt;();
      }
  }
  
  public static class LinqUtilities
  {
      public static HashSet&lt;T&gt; ToHashSet&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)
      {
          HashSet&lt;T&gt; hashSet = new HashSet&lt;T&gt;();
  
          foreach (var en in enumerable)
          {
              hashSet.Add(en);
          }
  
          return hashSet;
      }
  }
  </code></pre>
  
  <p>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 <code>IEnumerable</code> to <code>HashSet</code> is causing a lot of overheads.
  <code>ToHashSet</code> is my extension method.
  This function is to slow and eating a lot of time.</p>