Isn’t Linq great?


The lack of ForEach extension method on types other than List meant I didn’t pay enough attention soon enough to Linq which is great to use. The fluent coding style, now I’m used to it, makes data management tasks seem easier (and here I mean management of POCO list and dictionaries not databases).

Here’s a problem that Linq resolves elegantly.

Suppose you have a list or dictionary and you want to iterate over that list to remove some items based on a criteria. Except you can’t do it directly because you can’t update a list while using its iterator. So you have to first run over the list (or dictionary) and record into temporary list the index (or key) of those items you want to delete. Then iterate over the temporary list to grab the index (or key) you recorded and used it to delete the item from the main list (or dictionary). Easy enough but a bit of a mess.

Here’s an example using Linq. In this case the dictionary recentlySent is defined as:

1
Dictionary<string,DateTime> recentlySent;
Dictionary<string,DateTime> recentlySent;
1
2
3
4
5
6
7
8
9
 recentlySent
   // Select entries that are over 10 seconds old
   .Where(f => { return f.Value.AddSeconds(10) < DateTime.Now; })
   // Reduce the information to just the key
   .Select(f => f.Key)
   // Realize the list
   .ToList()
   // Remove any aged items
   .ForEach(f => recentlySent.Remove(f));
 recentlySent
   // Select entries that are over 10 seconds old
   .Where(f => { return f.Value.AddSeconds(10) < DateTime.Now; })
   // Reduce the information to just the key
   .Select(f => f.Key)
   // Realize the list
   .ToList()
   // Remove any aged items
   .ForEach(f => recentlySent.Remove(f));

Of course under the covers this fragment is realizing a temporary list, that’s what the .ToList() method does. But it is a more fluent approach to the problem though if your’re not into lambda functions the where, select and foreach method may look mysterious..

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!