问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/573026/how-to-convert-this-code-to-linq