title: Linq to objects - select first object
body: <p>I know almost nothing about linq.</p>
  
  <p>I'm doing this:</p>
  
  <pre><code>var apps = from app in Process.GetProcesses()
      where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero
      select app;
  </code></pre>
  
  <p>Which gets me all the running processes which match that criteria.</p>
  
  <p>But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this</p>
  
  <pre><code>var matchedApp = (from app in Process.GetProcesses()
      where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero
      select app).First();
  </code></pre>
  
  <p>which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I'm actually trying to find the first matching item, and call <code>SetForegroundWindow</code> on it</p>
  
  <p>I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?</p>
  
  <pre><code>var unused = from app in Process.GetProcesses()
      where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero
      select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
  </code></pre>