title: Custom Linq Extension Syntax
body: <p>I have written a function that gets a given number of random records from a list.  Currently I can do something like:</p>
  
  <pre><code>IEnumerable&lt;City&gt; cities = db.Cites.GetRandom(5);
  </code></pre>
  
  <p>(where db is my DataContext connecting to a SQL Server DB)</p>
  
  <p>Currently, I have a function like this in every entity I need random records from:</p>
  
  <pre><code>public partial class City
  {
  
      public static IEnumerable&lt;City&gt; GetRandom(int count)
      {
          Random random = new Random();
          IEnumerable&lt;City&gt; cities = DB.Context.Cities.OrderBy( c =&gt; random.Next() ).Take(count);
  
          return cities;
      }
  
  }
  </code></pre>
  
  <p>It works fine, but I'd like it to be generic, so it can work for any table, or even any list of items.  I have tried an extension method like:</p>
  
  <pre><code>    public static IEnumerable&lt;T&gt; GetRandom&lt;T&gt;( this Table&lt;T&gt; table, int count)
      {
          Random random = new Random();
          IEnumerable&lt;T&gt; records = table.OrderBy(r =&gt; random.Next()).Take(count);
  
          return records;
      }
  </code></pre>
  
  <p>but I get:</p>
  
  <pre>
    Error 1   The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table' 
  </pre>
  
  <p>which highlights <code>GetRandom&lt;T&gt;</code>.</p>
  
  <p>I don't understand what the problem is here.  Can someone clear up the proper syntax?</p>