Wednesday, October 7, 2009

LINQ / Lambda Examples : Aggregate collection


///////////////////////////////////////////////////////////////////////////////
//
// Copyright © Schakra Inc. 2009. All rights reserved.
//

///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Schakra.Samples.DotNet.Linq
{
///
/// Sample demonstrating aggregating content of a Collection.
///

public class LinqSample_02
{
public void AggregateRequestParameters()
{
// Generate Data.
Random random = new Random();
List uids = new List();
for (int i = 0; i < 10; i++)
{
uids.Add(random.Next(1, int.MaxValue));
}

// Had to use similar code snippet while working with Facebook APIs.
string uidString = uids.Aggregate(
string.Empty,
(s, uid) => string.Format("{0},{1}", s, uid.ToString())
// (s, uid) => s + "," + uid.ToString())
).Substring(1);

// Had to use similar code while working with OAuth signature creation.
SortedList oauthParams = new SortedList();

// Append all parameters in sorted order.
string sigBaseString = oauthParams.Aggregate(
string.Empty,
(s, kvp) => string.Format(
"{0}&{1}={2}", s, UrlEncode(kvp.Key), UrlEncode(kvp.Value))
).Substring(1);
}

private static Regex hexCharsExp = new Regex("%.{2}", RegexOptions.Compiled);

// Custom encoding in upper case for OAuth String.
private static string UrlEncode(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

return hexCharsExp.Replace(
HttpUtility.UrlEncode(input), m => m.Value.ToUpper());
}
}
}