Thursday, February 05, 2009

LINQ expression syntax

I have been recently starting to use LINQ expression syntax a little more. One refactoring that I have been doing is changing things like:

foreach(SomeItem item in items) {
    if(item.SomeProperty == someValue) {
        item.DoSomething();
    }
}

into the slightly nicer:

foreach(var item in (from i in items
                     where i.SomeProperty == someValue
                     select i)) {
    item.DoSomething();
}

… My only hesitation is the nastiness of the syntax (if you try to get it inline with no extra variable definitions – yes I know the extra parentheses are not required, but I find var item in from i in items to be very unreadable, plus I am often adding method syntax to these things at a later stage)… Some syntactic sugar might be nice to get:

foreach(var item from items                                      
                 where item.SomeProperty == someValue                 
                 select item) {
    item.DoSomething();
}

There is probably also a higher order function way to do this for simple cases of just calling one function on each match, but most of the time the code is not as simple as a single method call. Ideally I would love to do something like:

(from i in items where i.SomeProperty == someValue select i).Map(DoSomething);

P.S. Do not like the new Windows Live Writer editor. I just want an editor that makes it easy to create nice neat mark-up! Why is it so difficult to NOT put in paragraphs and other containers that I don’t need? And why can’t I see them in edit mode? And why do I drop out of the edit container and then have the backspace key delete the whole container?

No comments:

Post a Comment