我想在LINQ中执行以下等效操作,但我无法确定如何执行:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
真正的语法是什么?
我想在LINQ中执行以下等效操作,但我无法确定如何执行:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
真正的语法是什么?
当前回答
MoreLinq有IEnumerable<T>.ForEach和许多其他有用的扩展。仅为ForEach使用依赖关系可能不值得,但其中有很多有用的东西。
https://www.nuget.org/packages/morelinq/
https://github.com/morelinq/MoreLINQ
其他回答
又一个ForEach示例
public static IList<AddressEntry> MapToDomain(IList<AddressModel> addresses)
{
var workingAddresses = new List<AddressEntry>();
addresses.Select(a => a).ToList().ForEach(a => workingAddresses.Add(AddressModelMapper.MapToDomain(a)));
return workingAddresses;
}
现在我们可以选择。。。
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 4;
#if DEBUG
parallelOptions.MaxDegreeOfParallelism = 1;
#endif
Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID));
当然,这打开了一个全新的线虫罐头。
ps(对不起,字体是系统决定的)
正如许多答案已经指出的那样,您可以自己轻松地添加这样的扩展方法。然而,如果您不想这样做,尽管我不知道BCL中有什么类似的内容,但如果您已经引用了Reactive Extension(如果没有,您应该有),System命名空间中仍然有一个选项:
using System.Reactive.Linq;
items.ToObservable().Subscribe(i => i.DoStuff());
虽然方法名称有点不同,但最终结果正是您所希望的。
如果您想充当枚举滚动,则应生成每个项。
public static class EnumerableExtensions
{
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (var item in enumeration)
{
action(item);
yield return item;
}
}
}
在Jon Skeet的启发下,我扩展了他的解决方案:
扩展方法:
public static void Execute<TSource, TKey>(this IEnumerable<TSource> source, Action<TKey> applyBehavior, Func<TSource, TKey> keySelector)
{
foreach (var item in source)
{
var target = keySelector(item);
applyBehavior(target);
}
}
客户:
var jobs = new List<Job>()
{
new Job { Id = "XAML Developer" },
new Job { Id = "Assassin" },
new Job { Id = "Narco Trafficker" }
};
jobs.Execute(ApplyFilter, j => j.Id);
...
public void ApplyFilter(string filterId)
{
Debug.WriteLine(filterId);
}