Thursday, April 29, 2010

LINQ

or should I say Ruby on Rails.NET?

Today I started experimenting with LINQ in the .NET 3.5 framework, and my first impression was "this looks so much like Ruby on Rails". I'm not complaining about this, because it makes my life soo much easier now that I can apply the knowledge I have about the Ruby on Rails framework with it's hashmaps and active directory to the .NET model with LINQ.

To demonstrate with a small piece of code that I have:
I have a List that is filled with Cell objects. Because I wish to make sure that each cell can only be added once to the List, I need to verify the names of the Cells in the list prior to adding the cell. So I made a special indexed property that uses a bit of LINQ.

The function body of my property looks like this:
public Cell this[String name]
So, if I wish to select the cell that matches the given name from my internal List object I need to call the following line of code:
return m_cells.Single(c => c.Name == name);
The line above will return a Single Cell object that has the specifed name and resides in the List collection. If no Cell matches the given LINQ expression and InvalidOperationException is thrown.

But because a property works in 2 ways, I need to make sure I can assign a cell as well. The logic behind the following function might be a bit weird, but I wish to be able to select a cell based upon it's name and assign it a new value. However I do not wish to add the same cell twice to the collection. To facilitate this I wrote the following code:

// Use LINQ to count the cells in the CellCollection with the specified name.
// We will perform a count on it, because we need to check if the cell is present.
Int32 cell_count = (from c in m_cells where c.Name == name select c).Count();
// Check if the specified cell was found in the collection.
if (cell_count == 0)
{
// Count 0 means the cell was not present in the first place, so
// add it at the end.
m_cells.Add(value);
}
else
{
// The cell is present, so locate it that we can overwrite it.
Cell cell = (from c in m_cells where c.Name == name select c).Single();

// Change the cell with the new value.
cell = value;
}
The above code does exactly what it's supposed to do. Overwrite the cell if it's already in the collection or add it at the end if it's not present.
LINQ makes writing code a bit trickier to understand, but it shortens the total amount of lines you need to write by ALOT.

No comments:

Post a Comment