Archive for the ‘LINQ’ category

LINQ Makes Life Easier

September 7, 2007


LINQ is really cool.  There are tons of examples on the web that show you how to use LINQ to query a database, xml file, text file or collection.  This is what LINQ will primarily be used for; to simplify and support the need to provide an association between external relational data and object oriented programming.  With LINQ, records can be extracted from a database and encapsulated into a type-safe object that you can use in .NET just like any other object.  In my opinion, this is really going to change the way that we develop data-driven applications.

The change is likely going to take some getting used to.  The first time you look at a LINQ expression, it just looks weird.  But after you start to understand it, you might realize that it is very similar to SQL statements (select..from..where..orderby).  Then it just clicks and you are off writing all kinds of crazy queries. 

Why are developers going to take the time to learn LINQ?  Personally, I think it makes life a lot easier.  Compare any SQL LINQ example on the web to the .NET 2.0 code that you would have to write to accomplish the same thing.  LINQ is more concise and easier to implement.

For example, let’s say that I want to create a collection that contains a reverse sorted list of filenames from a certain directory.  I also want to have the associated creation time, last access time, and last write time for each file.  Well I could create a class that implements these properties and then populate instances of the class in a collection by doing something like “foreach (string f in Directory.GetFiles(path))” and then calling the appropriate File methods to fill in the data that I want.  Not to hard, just a simple class definition and then a loop and a few method calls.

What if I could do all of that in less than 10 lines of code?  

var files =
from file in Directory.GetFiles(@"c:\windows")
orderby file descending
select new
FileName = file,
CreationTime = File.GetCreationTime(file),
LastAccessTime = File.GetLastAccessTime(file),
LastWriteTime = File.GetLastWriteTime(file)

Is that not a much easier way of doing it?  And then you can use the “files” object just like any other collection to consume the data.

foreach (var file in files)
Console.WriteLine("{0}\n\tC: {1}\n\tA: {2}\n\tW: {3}\n",

There are so many uses for this beyond just the database and file arenas.

LINQ Makes Life Easier