Monday 17 May 2010

Linq equivalent of for-each

If you've ever wondered about using Linq for a more elegant implementation of a for each loop then this may be useful, use the Select<> method to perform actions against a set of items, as long as you return a value of any sort then you can perform any action during the selection.

In the example below I need to remove all folders that were written to over an hour ago, it also returns info on the folders processed and whether they were successfully removed:


if (string.IsNullOrEmpty(RootWorkingFolder) || !Directory.Exists(RootWorkingFolder)) return;

Directory.GetDirectories(RootWorkingFolder)
.Where(f => Directory.GetLastWriteTime(f) < DateTime.Now.AddHours(-1))
.Select(delegate(string f)
{
try
{
Directory.Delete(f, true);
return new {Folder = f, Removed = true};
}
catch (IOException)
{
return new {Folder = f, Removed = false};
}
}).ToList();


The ToList method is to ensure that the query is executed immediately.

Pretty useful to know :-)

No comments: