Rediscovering the Obvious

…stumbling in the footsteps of greatness

Linq is GREATNESS!

without comments

Freaking amazing.

Scenario: I need to load the contents of a table into a dictionary of objects keyed by one of the fields.

Before: Write the ORM code to load the entire table. (3 lines) Initialize the dictionary (1 line). Write the for each loop to move each instance from the ORM’s collection type into the dictionary (3 lines).

After: Write the link query to get the day, then use an extension method + lambda to build the keyed dictionary and assign the result to the dictionary field (1 line).

Wow!

myDictionary = db.UsageTypes.ToDictionary<UsageType, int>( t => t.UsageTypeID);
 

The only thing I can’t find is the basic extension method that would serve as essentially a foreach. All of the ones I’ve investigated on the IList<> extension list seem to be filtering and grouping… the .All<> seems like it SHOULD work, but it still expects a boolean return for filtering. I want something where I can do an operation with a simple side effect, like call add on another list (I know there’s better ways, but I’m trying to generalize a bit). I want something like:
myListOfT.Apply<T>( t => otherThing.SomeMethod(t));

 

[EDIT]

The concept I’m looking for is myListOfT.Action<T>( lambda ), but I still don’t see it in the library… it’s just implied from some things I was reading on the Parallel Development forums on MSDN.

[EDIT2]

DUH!  List.ForEach<T>(Action<T>()). Just only exists on the list, not on the interface.
 

Written by erwilleke

February 11th, 2008 at 2:19 pm

Posted in Uncategorized

Leave a Reply