I've been casually working on a C# jQuery port. Why would you do this, you might ask? Well, ostensibly, it's because I found myself in a situation where I needed to do some HTML parsing for a CMS driven application. I needed to process the CMS-served content in order to make it possible to include functional elements in the content. I had an awful bit of code I'd hacked together a long time ago to deal with this, but I thought it wouldn't be too hard to create a basic jQuery port (with a simple subset of its functionality) for this purpose, rather than doing something like learning how to use the HTML Agility Pack. And I sort of wanted to do it for fun. (Yes, I have odd ideas about fun...)
Turns out, the hardest part by far was just parsing the HTML in the first place. jQuery is so elegant in its simplicity and the way it builds upon itself, once I'd gotten a basic infrastructure set up that turned some HTML into an object tree, implementing selectors and each additional function took less and less time. I got the thing basically working in about a day, and with enough features to solve my problem in two.
But I digress. One of the things I implemented first was each
. I'd never given much thought to such a thing before, but it turned out to be astoundingly simple:
public CsQuery Each(Action<DomElement> func)
{
foreach (DomElement obj in Elements)
{
func(obj);
}
return this;
}
Usage looks like this, using lambda notation:
someObj.Each(e =>
{
});
or using delegate
:
someObj.Each(delegate(DomElement e) {
});
Starting to look awfully familiar isn't it... well, chaining isn't exactly new to C#, as LINQ popularized the concept a while ago, and there's already a ForEach
method on List
objects. But I can't say I've seen a lot of code that looks like this outside of jQuery. Since doing a lot of jQuery in the last year or two, though, I have come to appreciate the elegance of the syntax so much that I decided to write an extension method for general use. It's essentially identical to the above:
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> list, Action<T> func)
{
foreach (T obj in list)
{
func(obj);
}
return list;
}
That's all there is to it. I used ForEach
(instead of Each
) just to maintain consistency with the List
and Array
methods. Now you can use that simple syntax with any IEnumerable<T>
instead of creating standalone foreach
structures, and chain and LINQ and iterate to your heart's content. Once you start, I swear you won't go back.