I expect there are a number of implementations of this around, but I couldn’t find one so I wrote this. It is an extension method which implements Fold on IEnumerable
public static class Extensions
{
public delegate TDestination FoldOperation<TSource, TDestination>(TSource item, TDestination acc);
public static TDestination Fold<TSource, TDestination>(this IEnumerable<TSource> list, FoldOperation<TSource, TDestination> foldOperation, TDestination acc)
{
foreach(TSource item in list)
{
acc = foldOperation(item, acc);
}
return acc;
}
}
I can then use this Fold function for something like this which takes an object with a number of properties and creates a querystring with the name/value pairs of all of those properties which are non-null:
public class UrlConstructor
{
//Takes a RequestParameter object with a number of properties which
//if their value is set should be translated into querystring parameters
public static string ConstructUrl(RequestParameters rp)
{
//Get all the properties where the value is not null
var values = typeof(RequestParameters).GetProperties().Where(p => (p.GetValue(rp, null) != null));
//Fold these values up into a string
var querystring = values.Fold(((p, acc) => acc + p.Name + "=" + p.GetValue(rp, null) + "&"), "").TrimEnd('&');
return "http://mybaseurl.com/default.aspx?" + querystring;
}
}
