Monday, September 28, 2015

Adventures in LINQ Enumerables Extension Methods

var a  = new List<string>{"A", "Z", "C", "D", "C"};
var b  = new List<string>{"G", "D", "E", "Z", "C"};
var c  = new List<int>{1, 1, 1};

System.Linq.Enumerable.Zip(a, b, (a1,b1)=> new {a=a1,b=b1}).Dump("Zip - creates a collection with elements from list a and b matched based on index position"); 
a.Zip(b, (a1,b1)=> new{a1, b1}).Dump("Zip - shorthand");

System.Linq.Enumerable.Aggregate(c, (resultsofar,y)=> resultsofar-y ).Dump("Aggregate1"); //first number is initial value for result so far and starting from second value, function recusrses
c.Aggregate (2000, (resultsofar, cn) => resultsofar+ cn).Dump("aggregate2"); //first argument is initial value, aggregator function is then evaluated for each item in collection

System.Linq.Enumerable.Range(101, 5).Dump("Range - generates a list of numbers starting from 101 to 105");

System.Linq.Enumerable.Except(a, b).Dump("Except - generates a list of containing items from a minus values from b.  Result is A, B"); 
a.Except(b).Dump("shorthand for except");

System.Linq.Enumerable.Union(a, b).Dump("Union - union of two lists, excluding duplicates");
a.Union(b).Dump("Union shorthand");

System.Linq.Enumerable.Concat(a, b).Dump("Concat - make two lists into one bigger list"); 
a.Concat(b).Dump("Union shorthand");

System.Linq.Enumerable.Intersect(a, b).Dump("Intersect - unique list of items which exist in both lists"); 
a.Intersect(b).Dump("Intersect shorthand");
See results of these statements below...