Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Created March 17, 2011 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tarnacious/874052 to your computer and use it in GitHub Desktop.
Save tarnacious/874052 to your computer and use it in GitHub Desktop.
Compiling SelectMany Linq without System.Linq. Also a List Monad.
using System;
using System.Collections.Generic;
public static class ExtensionMethods
{
public static IEnumerable<T> ToList<T>(this T value) {
yield return value;
}
public static IEnumerable<U> SelectMany<T, U>(this IEnumerable<T> m, Func<T, IEnumerable<U>> k)
{
foreach (var x in m)
foreach (var y in k(x))
yield return y;
}
public static IEnumerable<V> SelectMany<T, U, V>(this IEnumerable<T> id, Func<T, IEnumerable<U>> k, Func<T,U,V> s)
{
return id.SelectMany(x => k(x).SelectMany(y => s(x, y).ToList()));
}
}
public class ListMonad
{
public static void WithExtensions()
{
IEnumerable<string> list1 = new string[] {"1", "2", "3"};
IEnumerable<string> list2 = new string[] {"c", "d"};
var r = list1.SelectMany(
x => list2, (x, y) => x + y);
foreach (var i in r)
Console.WriteLine(i);
}
public static void WithLinq()
{
IEnumerable<string> list1 = new string[] {"1", "2", "3"};
IEnumerable<string> list2 = new string[] {"c", "d"};
var r = from x in list1
from y in list2
select x + y;
foreach (var i in r)
Console.WriteLine(i);
}
public static void Main()
{
Console.WriteLine("With Extension Methods");
WithExtensions();
Console.WriteLine("");
Console.WriteLine("With Linq");
WithLinq();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment