title: Linq avoid calling function twice
body: <p>Using Linq to Objects a query might need to filter based on the result of a function and return the value of that function.</p>
  
  <p>For example</p>
  
  <pre><code>files.Where(x =&gt; string.IsNullOrWhiteSpace(x.getProperty(propName)))
                  .GroupBy(x =&gt; x.getProperty(propName));
  </code></pre>
  
  <p>Does the compiler recognize that the value is going to be required for grouping and keep it?</p>
  
  <p>If it doesn't then there must be a way to select to an anonymous type and query the Where and GroupBy statements against that. Is it possible to do this with an anonymous type?</p>
  
  <p>I am able to declare a class and use that. </p>
  
  <pre><code>class fileSelector
  {
      internal string prop;
      internal myFile file;
  }
  
  var groups = files
       .Select(x =&gt; new fileSelector() { prop = x.getProperty(propName),  file = x })
       .Where(x =&gt; !string.IsNullOrWhiteSpace(x.prop))
       .GroupBy(x =&gt; x.prop);
  </code></pre>
  
  <p>But is there a way to do this with an anonymous type?</p>
  
  <p>This is what I tried for an anonymous type</p>
  
  <pre><code>var groups = files.Select(x =&gt; new { x.getProperty(propName),  x })
                    .Where(x =&gt; !string.IsNullOrWhiteSpace(x.prop))
                    .GroupBy(x =&gt; x.prop);
  </code></pre>
  
  <p>But this gives the error </p>
  
  <p>Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.</p>
  
  <p>Final answer</p>
  
  <pre><code>var groups = files
       .Select(x =&gt; new { prop = x.getProperty(propName),  file = x })
       .Where(x =&gt; !string.IsNullOrWhiteSpace(x.prop))
       .GroupBy(x =&gt; x.prop, x =&gt; x.file);
  </code></pre>