Posts

Showing posts with the label functional programming

C# Extension to split IEnumerable into batches of n items

This code splits a list into a batches on n items. If list = (1,2,3,4,5,6,7,8,9,10) and n = 3 then the result is ((1,2,3),(4,5,6),(7,8,9),(10)) public static class Extensions { public static IEnumerable<IEnumerable<T>> Batch<T>( this IEnumerable<T> list, int batchSize) { int i = 0; return list.GroupBy(x => (i++ / batchSize)).ToList(); } } [TestFixture] public class TestExtensions { [Test] public void TestBatch() { var list = new List< int >() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = list.Batch(3).ToList(); Assert.AreEqual(4, result.Count()); Assert.AreEqual(3, result[0].Count()); Assert.AreEqual(3, result[1].Count()); Assert.AreEqual(3, result[2].Count()); Assert.AreEqual(1, result[3].Count()); result.ForEach(x=>Console.WriteLine( string .Join(" , ",x))); } }

C# LINQ GroupBy example

public void TestGroupBy() { var people = new [] { new { Name=" John ", City=" London ", Side=" South ", Age=20}, new { Name=" John ", City=" London ", Side=" North ", Age=55}, new { Name=" Eli ", City=" London ", Side=" North ", Age=39}, new { Name=" Anna ", City=" NY ", Side=" North ", Age=23}, new { Name=" Marc ", City=" NY ", Side=" South ", Age=51}, new { Name=" Julie ", City=" NY ", Side=" South ", Age=67}, }.ToList(); var ageByCitySide = people .GroupBy(p => new {p.City, p.Side}) .Select(r => new {r.Key.City, r.Key.Side, AverageAge = r.Average(p => p.Age)}) .OrderBy(p=>p.AverageAge); foreach (var p in ageByCitySide) { Console.WriteLine(" {0},{1} AvgAge:{2} ",p.City,p.Side,p.AverageAge); } var youngOldBy...

Functional Programming in C# 3.0

Tutorial on using Functional Programming (FP) techniques Query Composition using Functional Programming Techniques in C# 3.0

C# Functional programming

namespace Test { public static class Extensions { //ForEach IEnumerable extension public static void ForEach<T>( this IEnumerable<T> source, Action<T> action) { foreach (var item in source) { action(item); } } } class Person { public string Name { get ; set ; } public string City { get ; set ; } } class Account { public string Name { get ; set ; } public string AccountName { get ; set ; } public double Amount { get ; set ; } public List< string > Cards { get ; set ; } } [TestFixture] public class TestFunc { private List<Person> people; private List<Account> accounts; [TestFixtureSetUp] public void SetUp() { people = new List<Person>(); people.Add( new Person(){Name=" J...