views:

170

answers:

2

I'm trying to write this as LINQ,

Original code:

For Each CurrentForm As Form In MyForms
    AddLink(CurrentForm.GetLink())
Next

I'm a LINQ beginner, so far I'm not quite sure where to use and where not to. If in this case LINQ will do more harm then help, feel free to flame me.

Edit : You can assume that there is an overload for AddLink() which takes IEnumerable

+3  A: 

Unless there is an overload of AddLink which takes a collection, LINQ won't avoid the loop.

Is there is such an overload then something like:

AddLinks(MyForms.Select(f => f.GetLink())

would do it.


How the above expression works (briefly):

  • LINQ is about expressions, taking some object (for LINQ to Objects used here, always a collection)
  • Select extension method takes a collection and a function and returns a collection. The function is passed each element of the input collection. And then Select returns the collection made up of all the function return values.
  • I have used a lambda expression to create an anonymous function that takes one argument called f (its type will be determined by the compiler) and returns the value of the expression (now corrected).
  • AddLinks is an assumed variant of your AddLink which takes a collection of links.

There is a lot going on, this is one of the advantages of LINQ, it is a compact way of expressing data manipulation without the usual overheads of explicit loops and temporary variables.

Richard
I assume this is C# (at least VS didn't like it in VB), I'm fine with converting any normal C# to VB.NET, but can't make any sense out of LINQ statements in C#
dr. evil
See update to answer coming.
Richard
Thanks for the update, just figured VB way to do it : AllLinks.AddRange(MyForms.Select(Function(xform) xform.GetAsLink(AttackResponse)))
dr. evil
Looks about right.
Richard
+2  A: 

No flames here, but LINQ won't really help here. If LINQ had a ForEach method (as has been discussed in a previous question, as well as elsewhere) then you could use that - but it's not built into LINQ, and in this case there doesn't really seem to be much use for it.

Of course, it depends exactly what AddLink does - if it adds a link to a list, and you could instead use (say) List.AddRange, then you could use LINQ. But this code seems pretty simple and readable already, so I wouldn't worry in this case.

Jon Skeet