Question

What is the functional programming approach to convert an IEnumerable<string> to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming.

Here's my example:

var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;

var delimitedString = ??

.. or could I do this in just the first var assignment (append each result to the previous)?

Was it helpful?

Solution

var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y);

OTHER TIPS

string.Join(", ", string[] enumerable)

Here's an example with a StringBuilder. The nice thing is that Append() returns the StringBuilder instance itself.

  return list.Aggregate( new StringBuilder(), 
                               ( sb, s ) => 
                               ( sb.Length == 0 ? sb : sb.Append( ',' ) ).Append( s ) );
var delimitedString = string.Join(",", checkboxList.Items.Where(i => i.Selected).Select(i => i.Value).ToArray());

AviewAnew is the best answer, but if what you are looking for is learning how to think in functional, what you should do is use a fold operation (or aggregate as it is called in NET).

items.Aggregate((accum, elem) => accum + ", " + elem);

Well, in this case the functional approach might not be best suited, simply because there isn't a LINQ "ForEach", and you don't want to use string concatenation: you want to use StringBuilder. You could use ToArray (an example just appeared above), but I'd be tempted to simply use:

    StringBuilder sb = new StringBuilder();
    foreach(ListViewItem item in checkboxList.SelectedItems) {
        if(sb.Length > 0) sb.Append(',');
        sb.Append(item.Text);
    }
    string s = sb.ToString();

Not functional programming, but it works... of course, if your source is already a string[] then string.Join is perfect. (LINQ is a great tool, but not necessarily always the best tool for every job)

Here's a LINQ/functional way of doing it.


string[] toDelimit = CallSomeFunction();
return toDelimit.Aggregate((x, y) => x + "," + y);

This is 3.5 compatible:

var selectedValues = String.Join(",", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top