我已经习惯使用Java的 Stream#Peek
方法,因为它是调试中间流操作的有用方法。对于那些不熟悉 Stream#Peek
的人 方法,下面显示了它的定义:
Stream<T> peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.
考虑下面这个简单的例子:
List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
.filter(i -> i % 2 == 0)
.peek(System.out::println)
.collect(Collectors.toList());
随着 Stream#Peek
方法,这应该基本上允许我将所有偶数打印到控制台,以便我可以测试看看这是否符合我的预期。
我试图找到手头问题的答案,但似乎无法在 C#
中找到类似的方法。 , 有谁知道 Java 的 Stream#Peek
的等价物 或其他具有类似行为的方法?
最佳答案
在 LINQ 中没有 Peek
的等价物 - 即没有执行某些操作的方法并且返回源元素。 List
类中有一个ForEach
方法,它对每个元素执行操作,但它不返回源元素,并且如前所述,它不是一个 IEnumerable
扩展。
但是你可以轻松地编写自己的扩展
public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (action == null) throw new ArgumentNullException(nameof(action));
return Iterator();
IEnumerable<T> Iterator() // C# 7 Local Function
{
foreach(var item in source)
{
action(item);
yield return item;
}
}
}
关于java - Linq C# 中 Java 的 Stream#Peek 方法的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44979936/