Search code examples
vb.netlinqlegacy

How to convert this code to LINQ?


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


Solution

  • 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.