blogs.conchango.com

welcome to the conchango blogging site
Welcome to blogs.conchango.com Sign in | Join | Help
in Search

Merrick Chaffer's Blog

Ultimate one liner? ForEach and anonymous methods

A colleague of mine recently asked for how to create a one liner to iterate over the items in a list. In C# 2.0 this is best done using the System.Action<T> delegate ForEach method, as it reduces the lines of code that you would normally write.

Easy way to think of it, is to write the foreach loop in the normal way, then change the foreach statement to say delegate, remove the text in the brackets of the foreach statement after and including the in statment (i.e. in areapaths), then put everything on one line, and surround it with normal brackets, and then put myList<t>().ForEach (ie. areapaths.ForEach at the start of the line and a semi colon at the end of the line.

Hence

List<string> areapaths = new List<string>();

foreach (string areapath in areapaths)

{

AddChild(dom, areasElem, Resources.AreaPath, areapath.Replace(project.Name, string.Empty));

}

Changes to this

areapaths.ForEach (delegate(string areapath) { AddChild(dom, areasElem, Resources.AreaPath, areapath.Replace(project.Name, string.Empty)); });

Job done!

Published 04 December 2006 11:24 by merrick.chaffer
Filed under: , , ,

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems