Some Linq Patterns

What follows is a list of a few patterns for specific tasks using LINQ

Combining two lists

We can combine two lists, where duplicates are removed using

var a = new List {0, 2, 3, 4, 5, 6};
var b = new List { 0, 1, 3, 4, 6, 6 };

var union = a.Union(b);
[/code]

Find the common items in both lists

var a = new List<int> {0, 2, 3, 4, 5, 6};
var b = new List<int> { 0, 1, 3, 4, 6, 6 };

var intersection = a.Intersect(b);

we can also use the lambda expression join

var l1 = new List<int> {1, 2, 4, 5};
var l2 = new List<int> { 0, 2, 4, 6 };

var r = from a in l1 join b in l2 on a equals b select a;

Find the differences between two lists

This will find the items in the first list which are not in the second list

var listA = new List<int> {0, 2, 3, 4, 5, 6};
var listB = new List<int> { 0, 1, 3, 4, 6, 6 };

var differences = from a in listA where listB.All(i => i != a) select a;

Combining every item in one list with every item in another list

Here we’re going to do a cross join, where the output enumerable is a made up of each element from the first list, combined with each element of the second list

var l1 = new List<int> {1, 2};
var l2 = new List<int> { 0, 2 };

var crossjoin = from a in l1
       from b in l2
       select new {a, b};

The output would be

1 0
1 2
2 0
2 2

I’ll add more as and when I remember to add them.