我想在LINQ中做相同的以下内容,但我无法弄清楚如何:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
Run Code Online (Sandbox Code Playgroud)
什么是真正的语法?
我有一个Enumerable<T>并且正在寻找一种方法,允许我为每个元素执行一个动作,有点像Select然后是副作用.就像是:
string[] Names = ...;
Names.each(s => Console.Writeline(s));
Run Code Online (Sandbox Code Playgroud)
要么
Names.each(s => GenHTMLOutput(s));
// (where GenHTMLOutput cannot for some reason receive the enumerable itself as a parameter)
Run Code Online (Sandbox Code Playgroud)
我试过了Select(s=> { Console.WriteLine(s); return s; }),但它没有打印任何东西.
我不明白为什么List<T>.ForEach()扩展方法for在引擎盖下实现了一个循环.这开辟了收集被修改的可能性.foreach在这种情况下,法线会抛出异常,所以肯定会ForEach()以同样的方式做出反应吗?
如果你因为某种原因必须改变一个集合,那么你肯定应该在循环中手动迭代集合for吗?
这里foreach和之间似乎有一点语义矛盾List<T>.ForEach().
我错过了什么吗?
我正在移植一些代码来使用Windows应用商店应用程序并注意到了 List<T>.ForEach方法未包含在.NET Core框架(Windows应用商店应用引用的框架)中.
MSDN确认Store Apps不支持它.
我可以很容易地绕过丢失的方法,但在这一点上我只是好奇为什么它丢失了.
我正在将Windows Phone应用程序移植到Win 8,我找到了这个绊脚石,但无法找到解决方案.
我有一个:
List<items> tempItems = new List<items>();
Run Code Online (Sandbox Code Playgroud)
和
ObservableCollection<items> chemists = new ObservableCollection<items>();
Run Code Online (Sandbox Code Playgroud)
我已经将项目添加到我的tempItems等,所以我这样做:
tempItems.OrderBy(i => i.Distance)
.Take(20)
.ToList()
.ForEach(z => chemists.Add(z));
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
Error 1 'System.Collections.Generic.List<MyApp.items>' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'System.Collections.Generic.List<MyApp.items>' could be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)
为什么会这样,Win8没有这个功能?我引用了以下内容:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Xml.Linq;
using Windows.Devices.Geolocation;
using …Run Code Online (Sandbox Code Playgroud) c# ×3
.net ×2
foreach ×2
linq ×2
windows-8 ×2
.net-4.5 ×1
c#-3.0 ×1
enumerable ×1
ienumerable ×1
list ×1