Dumping a formatted IEnumerable to Output


This blog post is a continuation from the preceding post LINQ Extension Method To Dump any IEnumerable. This blog post presents another LINQ extension method, which addresses, and provides a solution to, the limitations of the preceding approach. The significant limitation of the preceding approach was that the return type of the method was a string. This returned string runs the risk of overflowing a strings capacity when the IEnumerablehas a large number of elements, and/or the object to be output generates large amounts of formatted output.

This blog post presents a method that has the intention of taking an IEnumerable and pushing the contained objects to an output facility. The types of output facility utilised should be user defined. Personally, I use the Debug Output Window (see: Diagnostic Messages in the Output Window), and text files. I expect that this method will support, through the design and implementation of the extension method, support any output facility.

The ToOutput Extension Method


Design Goals

This extension method attempts to achieve two sets of design goals. These design goals were:

Design Goals from the ToPrintString Implementation
The method uses an unconstrained type parameter to describe the objects in the input IEnumerable.
The method uses an unconstrained type parameter to describe the objects in the input IEnumerable,
The method consumes Lambda Expressions, or delegates, to supply user-defined functionality.
The method used optional parameters for the parameters that supply used defined functionality.
The method supplies meaningful default actions for any omitted parameter.
  • Improve on the efficiency and flexibility of the previous method (the ToPrintString extension method presented in by blog post LINQ Extension Method To Dump any IEnumerable ) and remove the potential limitation on the maximum size of a string. The design goals to achieve this aim were:
Enable the emitting of each object in the IEnumerable directly to the output target.
Enable an output function is as flexible as possible.
The output function must accept a Lambda Expression, or a delegate.
Have a return from the function that will not suffer any possible overflow, or out of memory, system runtime exceptions.

Method Implementation – The Function Signature

The implementation of the ToOutput extension method has the following function signature.

public static long ToOutput<TSource>(this IEnumerable<TSource> Input,
    Func<TSource, int, bool> WherePredicate = null,
    Func<TSource, int, string> FormatFunction = null,
    Func<string, bool> OutputFunction = null,
    bool SummaryCount = true)

The function signature has the following features that address the design goals:

  • As with the ToPrintString extension method, the type that the type parameter TSource will accept has no constraints. This maximises the type of object that this extension method will accept.
  • The argument Input is the attribute of the function signature that makes this method an extension method. Specifically, allows the compiler to make the extension method association between this extension method and the interface type IEnumerable of T. The interface IEnumerable of T is the interface that the LINQ extension methods manipulate.
  • All of the extension method arguments are options, apart from the mandatory Input argument.
  • The arguments FormatFunction and OutputFunction supply a meaningful default implementation if the argument is null.
  • The arguments WherePerdicate and FormatFunction use an int argument. This int value is the position of the object in the input IEnumerable.
  • As with the ToPrintString extension method, this extension accepts a WherePerdicate argument. This argument allows the methods caller to specify a Lambda Expression, or delegate, which will select the objects in the Input IEnumerable processed by the extension method.
  • The argument OutputFunction is one of the additions to the ToOutput over the ToPrintString extension method. The LINQ extension method LongCount invokes argument OutputFunction. The use of the LongCount LINQ extension method is why the return type of the Lambda Expression, or delegate, is a bool. This result is indicating success, or failure, of the output operation.
  • The function argument SummaryCount controls the writing of a summary count through the OutputFunction. This may be useful if the output destination is a UI control.

Method Implementation – The Full Method Implementation

The following is the implementation of the ToOutput extension method.

For those who would like the source code in a file, I have loaded the code as a Word Document (.docx format) and a PDF to:
https://craigwatson1962.files.wordpress.com/2012/02/tooutput_cs1.docx , and
https://craigwatson1962.files.wordpress.com/2012/02/tooutput_cs1.pdf .
I hope that readers who want to use the source code for this method will find this an acceptable way of sharing the source. It should be a simple copy and paste operation to load this code into Visual Studio, or your C# preferred development environment. These files also include the xml comments (see: XML Documentation Comments (C# Programming Guide) for further information) for the method. These xml comments will enable IntelliSense (see: Using IntelliSense for further explanation) for the method extension.

public static long ToOutput<TSource>(this IEnumerable<TSource> Input,
    Func<TSource, int, bool> WherePredicate = null,
    Func<TSource, int, string> FormatFunction = null,
    Func<string, bool> OutputFunction = null,
    bool SummaryCount = true)
    if (FormatFunction == null)
        FormatFunction = (InputObject, Position) =>
            string.Format("[{1}] {0}, ", Position, InputObject);
    if (OutputFunction == null)
        OutputFunction = (StringRepesentation) =>
            return true;
    long ElementsDone = 0L;
    if (WherePredicate == null)
        ElementsDone = Input
            .Select((InputObject, Position) => FormatFunction(InputObject, Position))
            .LongCount((StringRepesentation) => OutputFunction(StringRepesentation));
    else {
        ElementsDone = Input
            .Where((InputObject, Position) => WherePredicate(InputObject, Position))
            .Select((InputObject, Position) => FormatFunction(InputObject, Position))
            .LongCount((StringRepesentation) => OutputFunction(StringRepesentation));

    if (SummaryCount)
        string OutputCount = string.Format("\nObjects Processed = {0:#,#}\n", ElementsDone);
        bool done = OutputFunction(OutputCount);
    return ElementsDone;

Method Implementation – Noteworthy Features

The following are notable elements in the implementation:

  • This extension method uses the LINQ method syntax to invoke extension methods the processing pattern.
  • The diagram below shows the LINQ methods composed to form the processing pattern used by this extension method. This extension method’s processing pattern is a series of LINQ method calls that pass the callers delegates to the LINQ implementation.

  • The use of Debug.Write as a default action for the OutputFunction is my choice for the most appropriate default action for my development efforts. If the reader has other thoughts on the matter, they are more than welcome to install their preference.

Sample Code Invoking the ToOutput Extension Method

The sample code demonstrates a series of calls to the ToOutput extension method. The sample code demonstrates calls to the ToOutput extension method that all use the LINQ method call syntax.

At present, I cannot think of how to use this extension method in the LINQ query syntax. The reason for that inability is that in the design of this method. This method’s design characterises a ‘data sink’. I would call something a ‘data sink’ if it is a process just that consumes an IEnumerable(of T) and does not produce a sequence.

The pattern of consume an IEnumerable(of T) and produce an IEnumerable(of T) would characterise a ‘transformation’. Methods that conform to the ‘transformation’ pattern are inherently linkable into chains of processes.

The following are links to the sample code stored in docx and PDF formats.


There a couple of thoughts I will raise in conclusion of the presentation of the ToOutput extension method. The thoughts include:

  • The development of LINQ extension method may appear daunting when you initially look at the topic. This is probably due to the syntax that the C# language requires to build an extension method is unfamiliar. I believe, and hopefully this and the proceeding blog posts demonstrates, that when you overcome that initial hurdle, implementing extension methods is not a significantly difficult process.
  • The use of Lambda Expressions or delegates to arguments to the extension methods is a very powerful and flexible implementation approach. This approach allows the abstraction between the pattern of processing and the actions applied at each step in the process. The extension method supplies the pattern of processing. The Lambda Expressions or delegates supply the caller-defined actions. This approach has much in common with functional programming approaches (see: Functional Programming topic in Wikipedia for an introduction to the topic).
  • This extension method does implement a solution that addresses, and resolves, the issue identified with the preceding blog post (LINQ Extension Method To Dump any IEnumerable). The strategy of writing directly to the output facility through the user supplied delegate, results in an implementation with a minimal memory requirement. Specifically, there is no dependence on the string object. This results in an implementation that cannot exceed the string objects finite capacity constraints.
    I have not evaluated whether this implementation is thread safe. A significant part the multi-thread safety of this extension method is dependent on the user’s implementation of the delegates passed into the extension method. The input delegates will need to be multi-thread safe to invoke this extension method the following fashion. The following is just one alternative for invoking this method in a parallel fashion.
    NB: This uses a “sledgehammer” to force parallel execution. The inclusion of the calls to AsUnordered() and WithDegreeOfParallelism(8) forces parallel execution, which is not what the ‘smarts’ in the implementation wants to do.
var Test1 = from counter1 in Enumerable.Range(0, 10000)
            select counter1;
var List1 = Test1.ToList();
var a = List1.AsParallel<int>().AsUnordered().WithDegreeOfParallelism(8).ToOutput(
        (objValue, position) =>
            string.Format("[{0}] {1}\n", position, objValue));

The following the Parallel Stacks screen snippet, shows the multiple treads. In addition, the output comes out in a nicely unordered sequence, indicating parallel threads are in action.

, , , , , , , , , , , ,

  1. LINQ Pivot, or Crosstab, Extension Method « Craig's Eclectic Blog
  2. C# Short Takes – 2 – String from IEnumerable « Craig's Eclectic Blog
  3. LINQ Short Takes – Number 4 –Make Union into a UnionAll « Craig's Eclectic Blog
  4. LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product « Craig's Eclectic Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: