C# 3.0 – Linq queries and Implicit Types

Finally played a bit with Linq today. About time, a lot of people will say, and rightly so. Just dipping my toes right now: wrote a short console application to list all current processes running more than 5 threads (no real use – just playing).

The whole thing was pleasantly intuitive, and the script is shown in its entirety below:

 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
using System.IO;  

namespace MyFirstLinq 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Process[] processes = Process.GetProcesses();  

            var query = 
                from process in processes 
                where 
                    process.Threads.Count > 5 
                orderby process.Threads.Count descending 
                select new { process.ProcessName, process.Threads.Count };  

            foreach (var result in query) 
                Console.WriteLine("{0} ({1} threads)", 
                    result.ProcessName, 
                    result.Count);  

            Console.ReadKey(); 
        } 
    } 
} 

While writing this, I also had a look at the implicit type declaration (the var keyword in the code) – already ran into this while talking to Marlon the C# Monk a few days ago (thanks again for taking the time to explain stuff – helps loads!). This form of declaration looks extremely handy – you get the benefits of strongly typed return values, without the hassle of having to write several small classes that are unlikely to be used anywhere else, ever (Annoying, but has my vote for the lesser of two evils – using object arrays for return values is messy).

According to MSDN, implicit types can only be used within the method scope. This makes sense, since if you’re going to start passing them around, you will probably need to declare a proper class for their values anyway.

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: