Concise C# Part 1 : Extension methods and Linq

Because, short code is easier to understand, I decided to publish some posts about making C# code shorter. I’ll talk about small tricks I use to significantly reduce the amount of code I write to achieve my goals. Some people don’t agree with that idea because there has been abuses done by perl and c programmer in the past. I think that, if you use correct names for methods, variable and types, the shortest code will still be easy to understand.

This post is part of a serie about making C# code shorter

In this post, I’ll use the following class for my examples :

Linq extension methods

Linq is a set of contracts (interfaces) wich allow the developper to request objects from a data store. What make it unique is that :
– the query language is strongly typed (at compile time you are sure that all column names et types are corrects and that there are no missin semi-colon
– it supports unlimited data store type (including all database systems, xml files, google data, twitter posts, in memory objects …)

I’ll focus primarily on Linq to Objects (in memory object) because we’re talking about making code concise. So here are the shortcuts !

Searching an unique element in a collection

Filtering a collection

Selecting a column (one property of an object collection)

Apply changes to a collection

Creating your own extension methods

Extension methods are the best candidates when you plan to build your very own low level toolset. Here are some examples to give you an idea.