Linq到对象-选择第一个对象 [英] Linq to objects - select first object

查看:69
本文介绍了Linq到对象-选择第一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对linq几乎一无所知.

I know almost nothing about linq.

我正在这样做:

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?

更新

我实际上是在寻找第一个匹配项,并在其上调用SetForegroundWindow

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

推荐答案

@FryHard FirstOrDefault将起作用,但请记住,如果未找到,则它返回null.此代码未经测试,但应接近您想要的代码:

@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);

这篇关于Linq到对象-选择第一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆