开发者

how do i make this NOT a loop?

how can i make this NOT a loop?

开发者_如何转开发
             {
             ManagementObjectSearcher Vquery = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
             ManagementObjectCollection Vcoll = Vquery.Get();
             foreach (ManagementObject mo in Vcoll)
             {
                 System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q=" + mo["name"].ToString());
             }


Here's a very stupid code to avoid foreach:

if( Vcoll.Count > 0)
{
   IEnumerator en = collection.GetEnumerator();
   en.MoveNext();
   System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q=" + en.Current["name"].ToString());
}

But, if the problem is opening multiple pages, I'd prefer a simple break in the foreach:

foreach (ManagementObject mo in Vcoll)
{
   System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q=" + mo["name"].ToString());
   break;
}


Here you are.

var procs = (from mo in (new ManagementObjectSearcher("SELECT * FROM Win32_VideoController")).Get().OfType<ManagementObject>()
                    select (System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q=" + mo["name"].ToString()))).ToList();


There are a few (fairly pointless) ways involving lists and methods like ForEach - or possibly Select, but you aren't solving a problem here. Just use the loop. It expresses perfectly what you are doing.

One hacky way (I don't recommmend this here):

Vcoll.Cast<ManagementObject>().Select(mo =>
    System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q="
        + mo["name"].ToString())).ToArray();

not an improvement IMO.


A common one-liner is:

Vcoll.ForEach( mo -> System.Diagnostics.Process.Start("http://www.google.com/search?hl=en&q=" + mo["name"].ToString()));

Of course ForEach has its own loop inside.


If all you want to accomplish is not opening pages twice, then use "distinct":

var foundNames = 
  (from ManagementObject mo in new ManagementObjectSearcher("SELECT * FROM Win32_VideoController").Get()
   let name = mo["Name"].ToString()
   where !String.IsNullOrEmpty(name)
   select name).Distinct();

foreach(var name in foundNames)
  Process.Start("http://www.google.com/search?hl=en&q=" + name);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜