如何在 linq 中调用没有返回类型的方法?
我喜欢在 linq 中或在 linq 的扩展方法中调用没有返回类型的方法? 在这里,我的班级有情况线,
Class A
{
int i;
public int K
{
get { return i; }
set { i = value; }
}
public void calculate(int z)
{
this.k=z;
}
}
我喜欢这样做,
List<A> sam = new List<A>();
//add elements to this list
var c = sam.Select( s => s.calculate(4) );
仅此示例,我喜欢这样做以达到我的目的。
i like to call a method without return-type in linq or in extension methods in linq?
Here my class i have situation line this
Class A
{
int i;
public int K
{
get { return i; }
set { i = value; }
}
public void calculate(int z)
{
this.k=z;
}
}
i like to do like this
List<A> sam = new List<A>();
//add elements to this list
var c = sam.Select( s => s.calculate(4) );
this sample only , i like to do like this for my purpose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该使用
List.ForEach
这里。我认为您在问题中使用
.Select
是因为您想获得结果(调用calculate
后 A 的所有实例)。您可以通过变量sam
直接获取它们。ForEach
修改 sam 的每个元素,并将“更改”应用于列表本身。You should use
List<T>.ForEach
here.I think you use
.Select
in your question because you want to get the results(all the instances of A after callingcalculate
). You can get them directly by the variablesam
.ForEach
modifies each elements of sam, and the "changes" are applied to the list itself.如果您的意思是要迭代序列 (IEnumerable) 并调用对于它的代码,您可以使用一个操作来实现扩展方法,该操作会为序列中的每个项目调用,例如:
如果您想调用小逻辑(一行)而不实现 foreach() 块,那么这是有意义的:
If you mean that you want to iterate a sequence (IEnumerable) and invoke code for it, you can inplement an extension method with an action, that is invoked for each item in the sequence, e.g.:
This makes sense if you want to invoke small logic (one line) without implementing a foreach() block:
如果不需要结果,可以用随机值填充结果(例如
false
)。If you don't need the result, you can fill the result with a random value (e.g.
false
).经常使用这种方法:
通用方法:
如果您想进行属性分配(额外奖励:示例如何使用 HTTP 客户端:-):
Using this often:
Generic approach:
If you want to do property assignment (bonus: example how to work with HTTP client :-):
我最近遇到了这个问题。我有时发现我更喜欢 LINQ 的声明语法...
这是我的调用,
我想不出让
AddToBasket()
返回任何内容的好理由,所以我重构如下:I recently ran into this issue. I sometimes find I prefer the declerative syntax of LINQ...
this was my call
I couldn't think of a good reason to make
AddToBasket()
return anything, so I refactored as follows:我最近有同样的需求,反应性地调用操作,并编写了一个 Do() 流处理函数,用于 1) 将操作包装到具有返回值的仿函数中,2) 在流上进行选择。
请注意,此实用程序函数仍然必须将流转换为 List() 才能逐字调用每个流项的操作。
I had the same requirement recently, call the action reactively and I write a Do() stream processing function for 1) wrapping the action into a functor with a return value and 2) selecting on the stream.
Please note that this utility function still has to convert the stream into List() to literally call the action for each stream item.