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...




Zip - creates a collection with elements from list a and b matched based on index position
(5 items)
ab
AG
ZD
CE
DZ
CC

Zip - shorthand
(5 items)
a1b1
AG
ZD
CE
DZ
CC

Aggregate1 -1 
aggregate2 2003 
Range - generates a list of numbers starting from 101 to 105
IEnumerable<Int32> (5 items)
101
102
103
104
105

Except - generates a list of containing items from a minus values from b.  Result is A, B
IEnumerable<String> (1 item)
A

shorthand for except
IEnumerable<String> (1 item)
A

Union - union of two lists, excluding duplicates
IEnumerable<String> (6 items)
A
Z
C
D
G
E

Union shorthand
IEnumerable<String> (6 items)
A
Z
C
D
G
E

Concat - make two lists into one bigger list
IEnumerable<String> (10 items)
A
Z
C
D
C
G
D
E
Z
C

Union shorthand
IEnumerable<String> (10 items)
A
Z
C
D
C
G
D
E
Z
C

Intersect - unique list of items which exist in both lists
IEnumerable<String> (3 items)
Z
C
D

Intersect shorthand
IEnumerable<String> (3 items)
Z
C
D

1 comment:

Mary Gooven said...
This comment has been removed by a blog administrator.