Posts Tagged .Net 4.0

In C# 3.0 (.Net 3.5/4.0) one can use the extension methods which work on IEnumerables to help with processing or converting your generic lists. This quick article shows how one can quickly join a list of integers and print them out as one sentance of “1 2 3 4 5”. Obviously there are other ways of doing this, but this gives one an overview.

Select Extension to Project Our List To Strings

Since the generic List<> inherits from IEnumerable we can use its extension methodd to do our dirty work. Look at the code here:

Line 05: We again use the Select extension/projection to convert our integers into string numbers.

Line 06: The aggregate method applies/projects an accumulator Lambda functon of our specification over the list of strings. Think of the Aggregate method as one which is stateful, for we will receive the results of the previous operation and be able to join it to the current. Line 04 simply tells the compiler that are working with two strings on input and output. One string is the previous aggregation operation and the other is the current item in the list being enumerated over during its processing.

Line 08: Since our aggregate takes two strings, we need to seed the process. The first call will use this string.Empty which will act as the first previous value to be married to the first current item in the projection/enumeration.

Line 09: This begins our declaration of the lamda function to use, it expects two strings, a previous accumulated string value and the current string item in the projection.

Line 10: What ever came before, we are going to marry it to the current. Here is why we need to seed string.Empty into the very first call.

Line 11: The previous will be married to the current, but we need to anticipate the very first time it is run where the string will be empty. For that situation, just return the current value. Otherwise return the current value with a space such as ” 2″. That will be then be concatenated (+) to prev in line 8. This is where we simulate the string.Join.

There you go a few ways of using the extension methods of Select and Aggregate and toArray with their specific individual lamda functions in C#.