views:

6864

answers:

3

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
+1  A: 

Assuming that in your first example apps is an IEnumerable you could make use of the .Count and .FirstOrDefault properties to get the single item that you want to pass to SetForegroundWindow.

var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;

if (apps.Count > 0)
{
    SetForegroundWindow(apps.FirstOrDefault().MainWindowHandle );
}
FryHard
+7  A: 

@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:

var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);
if (app == null) return;
SetForegroundWindow(app.MainWindowHandle);
Matt Hamilton
how do u put that in as a query and not an extension method?
Quintin Par
@Quintin there's no "keyword" syntax for FirstOrDefault - you have to use the extension method.
Matt Hamilton
+1  A: 

@FryHard If you're checking that Count > 0 then surely First() will never fail and that can be used rather than FirstOrDefault()?

ICR