LINQ doesn’t have to be about databases…


I'm finally getting into the groove with LINQ and lambda expressions, and am over the initial skepticism I had regarding the feature. My initial reaction was based on using LINQ for DB access, and was along the lines of "Pfft. There's no way I'm embedding SQL [essentially] in my code - think of the maintenance!"

(I've since re-thought that somewhat, but that's another story)

Putting databases completely aside, it took me some time to realize how much LINQ can really shine. So much of programming is about taking some data, querying it, and then doing something with it. Remember when you first started using foreach loops, and how they felt so much cleaner than for/while loops? Well, the jump to LINQ/lambda is so much greater in legibility and simplicity.

I'm not talking about hard-core stuff like a ray-tracer in one LINQ expression, I'm talking about simple every day things that would normally require a loop and some state. Some hypothetical examples (forgive my compiler-less syntax):

 

Find the closest point from a set of points:

   1: Point closestPoint = (from p in myPath.Points
   2:                       orderby DistanceBetween(p, myPoint) ascending
   3:                       select p).Take(1).Single(); 

Simple collision detection:

   1: List<PhysicsObject> collisionObjects = (from o in _AllObjects
   2:                              where o.DoesCollideWith(myObj)
   3:                              select o).ToList<PhysicsObject>(); 

Finding the distinct set of first names from all the people you know:

   1: var distinctFirstNames = (from p in _AllPeople
   2:                          select p.FirstName).Distinct();

Reset a property for all items in a list:

   1: _AllPlayers.ForEach( p => p.DamageTakenThisRound = 0 );

 

Try to recreate those using traditional loops and see how the code reads in comparison. LINQ is a thing of beauty! And consider what happens when PLINQ is in play, and your code is automatically multi-core aware.

The more I get used to doing this, the more places I realize it applies; the more I feel like I'm writing my program rather than trying to speak the compiler's language.

Next time you see a loop - ask yourself whether it really needs to be there...

Avi


Comments (1)

  1. Jim Wooley says:

    You have come to that critical place of understanding. LINQ is NOT about working with databases. LINQ is a much broader concept as it is an abstraction layer for set based operations.

Skip to main content