What is the equivalent of Java's Stream#Peek method in Linq C#?

Ousmane D. :

I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

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.

Consider this simple example below:

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

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

Sergey Berezovskiy :

There is no equivalent of Peek in LINQ - i.e. there is no method which performs some action and returns source elements. There is a ForEach method in List class which performs an operation on each element, but it does not return source elements, and as already said, it's not an IEnumerable extension.

But you can easily write your own extension

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;
       }
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=443924&siteId=1
Recommended