This question already has an answer here:
-
.Net lambda expression— where did this parameter come from?
5 answers
So I was looking around on the internet reading up on sorting techniques and I stumbled on to lambda.
Now i'm not completly sure how it works and i couldnt find any tutorials that broke it down to my level.
This is what im trying to break down.
var sorted = list.OrderBy(x => new MailAddress(x).Host).ToList();
So I get that I create a variable named sorted and this will be the variable that hold the sorted items from the list.
This is the part I dont understand
OrderBy(x => new MailAddress(x).Host)
Where does x come from and what exactly does the lambda expression mean? =>
Its not like this expression !=
which means NOT.
And I get that it sorts by host so Yahoo, GMAIL & Hotmail.
In simplest terms, x is a variable that you declare.
So it reads "x such that x is"... Whatever expression you are trying to convey based on the input and output parameter of your query.
To give you another example:
var sorted = list.Where(x => x.Name == "Foo").ToList();
This reads as "x such that x is equal to Foo". And this will return all list with Name property that is equal to Foo.
To further explain this, lets look into the one of the overloaded Enumerable method which is "Where". According to MSDN:
The actual syntax is:
Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
To give another example lets declare a List of integer. Our goal is to get all even integers:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Now to query all integers who are even numbers, we will use the one of the overloaded version of Where extension methods, using lambda syntax. It says:
So the source here is the:
numbers.Where();
Since "numbers" variable is the IEnumerable of TSource.
TSource here is any IEnumerable of type "T" or any type of entity.
Now the last part is it accepts a Func. A Func is a predefined delegate type. It provides us a way to store anonymous methods in generalized and simple way. To further understand this, lets read it again. It says that it will accept a source, and will output a boolean result.
Now let's create a Func that accepts TSource, on this case, integer as our example and will output boolean result:
Func<int, bool> fncParameter = x => x % 2 == 0;
Now we can pass that into our:
numbers.Where
Which will be:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Func<int, bool> fncParameter = x => x % 2 == 0;
IEnumerable<int> result = numbers.Where(fncParameter);
Or in short:
ist<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result = numbers.Where(x => x % 2 == 0);