Linq to objects - select first object

I recognize virtually absolutely nothing concerning linq.

I'm doing this:

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

Which obtains me all the running procedures which match that standards.

Yet I do not recognize just how to get the first one. The instances I can locate on the net appear to indicate I need 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 rather hideous, as well as additionally tosses an exemption if there are no matching procedures. Exists a far better means?

UPGRADE

I'm in fact searching for the first matching thing, and also call SetForegroundWindow on it

I've thought of this remedy, which additionally strikes me as hideous and also horrible, yet far better than above. Any kind of suggestions?

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
0
2019-05-18 22:18:27
Source Share
Answers: 2

Assuming that in your first instance applications is an IEnumerable you can take advantage of the.Count and.FirstOrDefault buildings to get the solitary thing that you intend 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 );
}
0
2019-05-21 06:41:13
Source

@FryHard FirstOrDefault will certainly function yet bear in mind that it returns null if none are located. This code isn't examined yet need to be close to what you desire:

var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);

if (app == null)
    return;

SetForegroundWindow(app.MainWindowHandle);
0
2019-05-21 05:47:50
Source