如何将此代码转换为LINQ? [英] How to convert this code to LINQ?

查看:113
本文介绍了如何将此代码转换为LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将其写为LINQ,

I'm trying to write this as LINQ,

原始代码:

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

我是LINQ初学者,到目前为止,我不确定在哪里使用和不使用.如果在这种情况下LINQ会带来更大的伤害,那么那么请帮助我.

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.

您可以假定AddLink()的重载需要IEnumerable

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

推荐答案

除非AddLink重载了一个集合,否则LINQ不会避免循环.

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())

会这样做.

上面的表达式是如何工作的(简短):

How the above expression works (briefly):

  • LINQ与表达式有关,它带有一些对象(对于LINQ此处使用的对象,总是一个集合)
  • 选择扩展方法需要一个集合和一个函数并返回一个集合.该函数传递给输入集合的每个元素.然后Select返回由所有函数返回值组成的集合.
  • 我已经使用 lambda表达式创建了一个匿名函数接受一个称为f的参数(其类型将由编译器确定)并返回表达式的值(现已更正).
  • AddLinks是您的AddLink的假定变体,它采用链接的集合.
  • 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.

发生了很多事情,这是LINQ的优点之一,它是一种表达数据操作的紧凑方式,而没有通常的显式循环和临时变量开销.

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.

这篇关于如何将此代码转换为LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆