Skip to content

Instantly share code, notes, and snippets.

@badmotorfinger
Last active August 29, 2015 13:58
Show Gist options
  • Save badmotorfinger/9968322 to your computer and use it in GitHub Desktop.
Save badmotorfinger/9968322 to your computer and use it in GitHub Desktop.
Using the SelectMany() God function.
void Main()
{
// An implementation of the Where method using the SelectMany() method.
TestWhere();
// An implementation of Join using the SelectMany() method.
TestJoin();
}
public static IEnumerable<T> Where<T>(IEnumerable<T> stuffs, Func<T, bool> predicate)
{
return
from i in stuffs
from i2 in ( predicate(i) ? new T[] { i } : new T[0] )
select i2;
}
public static IEnumerable<V> Join<T, TKey, U, V>(
IEnumerable<T> innerCollection,
IEnumerable<U> outerCollection,
Func<T, TKey> innerKeySelector,
Func<U, TKey> outerKeySelector,
Func<T,U,V> resultSelector) {
var outerLookup = outerCollection.ToLookup(o => outerKeySelector(o));
return
from i in innerCollection
from o in outerLookup[innerKeySelector(i)]
select resultSelector(i, o);
}
void TestWhere() {
var numbers = Enumerable.Range(0, 10);
var results = Where(numbers, n => (n & 1) == 1);
CollectionAssert.AreEqual(new[] {1, 3, 5, 7, 9}, results);
}
void TestJoin() {
var customers = new[]
{
new { ID = 1, Name = "John" },
new { ID = 2, Name = "Mary" },
new { ID = 3, Name = "Hank" }
};
var purchases = new[]
{
new { Product = "Tablet", CustomerID = 1 },
new { Product = "iPhone", CustomerID = 2 },
new { Product = "LINQPad", CustomerID = 2 },
new { Product = "ReSharper", CustomerID = 3 }
};
var results = Join(
customers, purchases,
c => c.ID, p => p.CustomerID,
(c,p) => new { c.ID, c.Name, p.Product } );
var expectedResults =
new [] {
new { ID = 1, Name = "John", Product = "Tablet" },
new { ID = 2, Name = "Mary", Product = "iPhone" },
new { ID = 2, Name = "Mary", Product = "LINQPad" },
new { ID = 3, Name = "Hank", Product = "ReSharper" },
};
CollectionAssert.AreEqual(expectedResults, results);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment