Convert to Linq!

While writing my last post, I was looking at the code to see if it was really something I wanted to post for general scrutiny and saw that I could use Linq to do the same thing. Here’s the old code:

bool visible = false;
foreach (var screen in Screen.AllScreens)
{
    if (screen.WorkingArea.Contains(this.DesktopLocation))
    {
        visible = true;
        break;
    }
}
if (!visible)
    this.Location = new Point(100, 100);

I changed it to (query syntax):

var visible = (from screen in Screen.AllScreens
               where screen.WorkingArea.Contains(this.DesktopBounds)
               select screen).Count() > 0;
if (!visible)
    this.Location = new Point(100, 100);

Or the extension method code:

var visible = Screen.AllScreens.Any(screen => 
    screen.WorkingArea.Contains(DesktopBounds));
if (!visible)
    this.Location = new Point(100, 100);

A quick run down of the conversion to the query syntax version:

  • The foreach turns in the the from line
  • The if predicate turns into the where line
  • The select and .Count() combine to form what I really want to know

I prefer the extension method syntax in this case, though. The call to Any() really says exactly what I want in a simple way. Any() will return true as soon as it finds an element that matches the supplied predicate.

Since my last post on Linq, I have used it to make code much more readable and succinct in this fashion. I love it.

This entry was posted in .Net, Linq. Bookmark the permalink.