LINQ set operations(extension methods) on arrays July 7, 2008
Posted by fofo in .NET, asp.net, C#, LINQ.Tags: extension methods, LINQ
trackback
In this post, which is another post for LINQ, I will try to explain how we can use LINQ set operators on arrays.Basically set operators are extension methods that allows to filter,merge arrays.We are going to examine these methods in detail. We will examine them by creating a project in visual studio.
Basically we are going to use two arrays of strings, countries and favcountries.
1) Launch Visual studio 2008 and create an ASP.net web application in C# in your filesystem
2) In the page load event of the default.aspx type the following
//create 2 string arrays
string[] countries = { “Britain”, “France”, “Croatia”, “Argentina”, “Australia”, “Mexico”, “Finland”, “Spain”, “Italy”, “Greece” };
string[] favcountries={“Britain”,”Argentina”,”Greece”,”Brazil”};
//cocatenate the string arrays with the Concat method
var thecountries = countries.Concat(favcountries);
foreach (var c in thecountries)
Response.Write(c);
if you hit F5 and run your application you will all the countries listed in both arrays
3) If we need to get only the unique values from the arrays we must comment out this line in the code above
var thecountries = countries.Concat(favcountries);
and type this
// only the unique countries appear with the union method
var thecountries = countries.Union(favcountries);
if you hit F5 you will see in your browser the number of the countries in those lists without duplicate values.
you can achieve the exact same thing if you do not type the line above , but this one
var thecountries = countries.Concat(favcountries).Distinct();
4) If you want to see only the values that are in both arrays, comment out the following line
var thecountries = countries.Union(favcountries);
and type this new line that uses the Intersect method
// countries that appear in both arrays
var thecountries = countries.Intersect(favcountries);
If you run your application only the dublicate countries will appear.
5) If you want to get the items that appear in the first array but not in the second array(not common items in the arrays, all the items in the first array that do not match with anything from the second array), you comment out this line of code
var thecountries = countries.Intersect(favcountries);
and type this
var thecountries = countries.Except(favcountries);
All these extension methods that enable us to filter, merge sequences live in the System.Collections.Generic namespace.
Good article goes into a lot of detail. I wrote a slim downed version which you can find at
LINQ operations Set Data