Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / C# 4.0

Display or format lists/collections/arrays using simple LINQ-style extension methods.

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
10 May 2013CPOL5 min read 14.6K   175   4  
This article provides and describes the EnumerableExt class, which simplifies the display and formatting of lists, collections, and arrays. It accomplishes this by implementing extension methods (Append, BuildString, and Write) that are available via the IEnumerable interface.

Introduction

Often, I've found myself writing code to display or format lists, collections, or arrays.   Most frequently, this is as simple as displaying a comma separated list, for example: item-1, item-2, item-3.   Occasionally, the requirements are a bit more complex.

This article describes a class (EnumerableExt) that can reduce the complexity of this task.   The class is implemented as a set of extension methods (Append, BuildString, Write) to the IEnumerable<T> interface.

Since almost all lists, collections, and arrays implement this interface, these methods become available via the magic of extension methods.

Background

Recently, I've been playing a lot with LINQ and enjoying the wonderful extension methods that it provides to the IEnumerable<T> interface.   It occurred to me that it would be comparatively simple to further extend the interface to include some methods that will, in the long run, make my life simpler.

This was the primary motivation in writing this code.   I am posting it here in case anyone else might also benefit.   The following source files are included with this article:

  • EnumerableExt.cs - This is the only file you need to take advantage of these new extension methods.
  • Program.cs - This console program simply demonstrates some of the features of the EnumerableExt class.
  • EnumerableExtTests.cs - This file can be used in a test project to test the features of the EnumerableExt class.

While knowledge of LINQ, extension methods, and lambda expressions are not necessary to use this code, I highly suggest learning these useful features of the C# language.   At the end of this article, I will include some links for further reading.

Using the code

To use this code, simply include EnumerableExt.cs in your solution.   In the class that consumes these methods, you will need to add the following using statement to make them visible:

C#
using Extended.Linq;

For demonstration purposes, in our example, we create a simple array of strings as follows:

C#
string[] list = new string[]{"Red", "Green", "Blue", "White", "Black"};

To write this array to the console, as a comma separated list, is as simple as follows:

C#
list.Write(Console.Out);

The resulting output (to the console) appears as follows:

Red, Green, Blue, White, Black

Extension Methods

Since this always seems a bit like magic to me, I'll take a brief moment to describe what happens.   If you are already familiar with extension methods, please feel free to skip ahead.  In fact, in that case, you may want to simply read the Program.cs to more quickly get a feel for how to use some of the options.

With extension methods, C# introduced a powerful new tool into the language.   By writing a static class, with static methods, and decorating the first parameter with the "this" keyword, you create an extension method. 

The C# compiler and IntelliSense are then smart enough, to make these methods visible to all classes that are the same type (or derived type) as that parameter.  The parameter type can be a class, struct, or interface.

In our case, the parameter type is IEnumerable<T> .  So, these extension methods become magically visible to anything that implements this interface.   In our example, they become visible to a string array.

More on using the code

Each of the methods, like Write, provide a number of overloads to include or omit optional parameters.   Here is an example of a slightly more complex write:

C#
list.Write(Console.Out, EnumerableExt.WriteDoubleQuote, " or ", element => element.ToUpper());

In this case, the output looks as follows:

"RED" or "GREEN" or "BLUE" or "WHITE" or "BLACK"

The parameters for this invocation are as follows:

  • writer - The TextWriter used to write the output.  In our case, we specified Console.Out to write to the console.
  • elementWriter - The ElementWriter (delegate from EnumerableExt) used to write an individual element to the output.  In our case, we specified EnumerableExt.WriteDoubleQuote.  This method is a convenience method from the EnumerableExt class, which writes the element surrounded by double quotes.  The EnumerableExt.WriteSingleQuote method is also available.  If neither of these methods meet your requirements, it is also quite easy to write your own method.
  • separator - The character sequence written to separate individual elements within the list.  In our case, we specified the string " or ".
  • selector - The function used to select individual elements.   In our case, we specified a lambda expression that simply uppercases the element.   If you are unfamiliar with the syntax for lambda expressions, a link is provided at the end of this article for further reading. 

Using the code to build strings

In addition to the Write method, there are two very similar methods provided to build strings: Append and BuildString.   The Append method appends to a pre-existing StringBuilder; whereas, the BuildString method creates its own StringBuilder, invokes Append on your behalf, and returns the resulting string.

As with the Write method, these methods provide a number of overloads so you can include or omit optional parameters.   Since the methods are so similar to Write, we will simply demonstrate the most complex method signature for each.

Rest assured, you do not need to provide all of the parameters demonstrated here.   The Program.cs file demonstrates the simple case of each method.

The following is an example of an invocation that uses all of the parameters for Append:

C#
list.Append(builder, EnumerableExt.AppendSingleQuote, " and ", element => element.ToLower());

You'll notice that the parameters are nearly identical to Write, with a StringBuilder replacing a TextWriter, and an ElementAppender replacing the ElementWriter.

It appends the following text to the StringBuilder:

'red' and 'green' and 'blue' and 'white' and 'black'

The following is an example of an invocation that uses all of the parameters for BuildString:

C#
string colors = list.BuildString(1024, EnumerableExt.AppendDoubleQuote, ":",
    element => element.ToUpper());

You'll notice that the parameters are nearly identical to Append, with an initial capacity (1024 characters) replacing the StringBuilder.  It returns a string containing the following text:

"RED":"GREEN":"BLUE":"WHITE":"BLACK"

Points of Interest

While the code is comparatively simple, and easy to implement, I've found it to be useful.   I hope you, the reader, will as well.

You may find the following reading helpful in further understanding some of the topics referred to in this article:

History

While I don't anticipate making a lot of changes to this article, here is its history, just in case:

  • 5/10/2013 - This is the original version of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Eric is a Senior Software Engineer with 30+ years of experience working with enterprise systems, both in the US and internationally. Over the years, he’s worked for a number of Fortune 500 companies (current and past), including Thomson Reuters, Verizon, MCI WorldCom, Unidata Incorporated, Digital Equipment Corporation, and IBM. While working for Northeastern University, he received co-author credit for six papers published in the Journal of Chemical Physics. Currently, he’s enjoying a little time off to work on some of his own software projects, explore new technologies, travel, and write the occasional article for CodeProject or ContentLab.

Comments and Discussions

 
-- There are no messages in this forum --