I know almost nothing about linq.
I'm doing this:
var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
Which gets me all the running processes which match that criteria.
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
var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?
UPDATE
I'm actually trying to find the first matching item, and call SetForegroundWindow
on it
I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?
var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess