How does Enumerable.Select work with lambda expressions? - c#

I am trying to understand how enumerables work in C# (and also how they work with lambdas) and have the following code that I was playing with.
bool[] boolArray = new bool[100];
boolArray = boolArray.Select(x => x != null).ToArray();
I understand Enumerables.Select will return an IEnumerable<bool> but how does the lambda expression, under the hood, act upon each element in the array? From my understanding the x on the left is the parameter which "goes to" the expression to the right of the => operator but it still doesn't feel like it should be enumerating.

Related

Confused by C# lambda expression

I have been learning about the lambda expression, I got happy when I finally can read/understand the => operator, it kind of means "where" to me
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(x => x>=5);
foreach (int x in b)
Console.WriteLine(x);
Reading the above line, personally makes sense to read it as "Find all x's from this list WHERE x is greater than or equal 5", very good.
But then I come across a different use of the lambda expression with the Select method.
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b1 = a.Select(x => x*2);
foreach (int x in b)
Console.WriteLine(x);
With this one, the previous way of reading this operator doesn't make sense, as to me this code does "For each x return x*2", which is very different "function" to what the same operator does in the previous case.
I understand that the difference is between .FindAll and .Select, different way of dealing with input and output parameters, but I am talking about the use of the operator => in the lambda expression.
There's no question in this question, so let's make one up.
Characterizing the lambda operator as "where" works when the lambda returns a bool and is used as a predicate to test a value. Is there a more general characterization of the lambda operator that makes sense in other contexts, such as projection?
Yes. Read the lambda operator as "goes to".
a.Select(x => x * 2);
"each x goes to x times two"
You can use that for predicates as well:
a.Where(x => x > 2);
"each x goes to 'is x greater than two?'"
But that's awkward. As you note, it is easier to think of this as "where" or "such that"
"each x such that x is greater than two"
Similarly
a.OrderBy(x => x.LastName)
"order each x by x goes to last name" is awkward. Just say "order each x by last name".
In short: the English language interpretation of the operator depends on the context. The formal interpretation of the operator is always the same: it simply describes a function.
The => operator has exactly the same meaning in both cases: it creates a function whose parameter is the thing on the left, and whose return value is the thing on the right.
You wrote in a comment that the x in the first case is not a parameter as you understand it. That's not correct; it is a parameter in both cases here.
Here's your first example, again:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(x => x>=5);
foreach (int x in b)
Console.WriteLine(x);
If you wanted to write this without using lambda notation, you would define a function somewhere, like this...
static bool MyCondition(int x)
{
return x >= 5;
}
...and then use that function as the argument to FindAll:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b = a.FindAll(MyCondition);
foreach (int x in b)
Console.WriteLine(x);
The lambda notation is a shorter notation which allows you to define the function right where you use it.
Likewise, if you wanted to write your second example without using lambda notation, you'd define a function elsewhere, like this...
static int MyOperation(int x)
{
return x * 2;
}
...and pass your function as the argument to Select, like this:
List<int> a = new List<int>(){0,1,2,1,3,4,5,6,7,8,9};
IEnumerable<int> b1 = a.Select(MyOperation);
foreach (int x in b)
Console.WriteLine(x);
Think of it this way:
Mathematics: f(x) = x + x
This is a mathematical function f that takes a number x and spits out its double.
Lambda: f = x => x + x C#'s way of defining the same function f.
Another example:
Mathematics: g(x, y) = x > y
g is a function that takes two numbers x and y and returns wether the former is greater than the latter.
Lambda: g = (x, y) => x > y C#'s way of defining the same function g.
Clearer now?
P.D: I've omitted talking about type inference and the type of the lambda's themselves; its an unnecessary distraction considering the context of this question.

what is the use of ()=> in silverllight

Can you say what is the use of the ()=> and =>? I saw this in a code. I did not get any reference for this.
this.Dispatcher.BeginInvoke(()=>
{
//some thing..
};
=> is the lambda operator in C# and is read as "goes to". A lambda expression is an anonymous function and can be used to create a delegate.
Your example takes no arguments as indicated by the empty parens preceding the lambda operator. A lambda expression with one argument might look like this:
n => n.toString()
That expression would return the string representation of n, when invoked. A lambda expression can have multiple arguments as well, contained in parentheses:
(n, f) => n.toString(f)
A common use would be in a Func<T>:
Func<int, string> getString = n => n.toString();
int num = 7;
string numString = getString(num);
This is, of course, a silly example, but hopefully helps to illustrate its use.
This notation is that of a lambda expression which takes no argument. If the lambda expression made use of arguments they would be declared in the empty set of parenthesis as in say...
this.Dispatcher.BeginInvoke((x, y) => { do some' with x and/or y }, 12, somevar);
In a nutshell, lambda expressions allows creating "nameless" functions, right where they are needed.
In the example of the question, the BeginInvoke() method requires its first parameter to be a delegate (a "pointer to a method"), which is exactly what this lambda expression provides.
It's a lambda expression that has no parameters.
Check out this page http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/
If you don’t have any parameters, like in our example, you use empty
paranthesis:
() => {…}

What does '=>' do in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Lamda Explanation and what it is as well as a good example
What is the => token called?
I have seen this code:
myContext.SomeEntities.Single(x => x.code == code);
And I don´t know what does the => operator do.
Every search on google about the operator returns no results.
Thank you.
The => operator designates a Lambda Expression:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
static void Main(string[] args)
{
Func<int, int> func = x => x * x;
int j = func(5);
// j == 25
}
Lambda expressions, very cool.
http://msdn.microsoft.com/en-us/library/bb397687.aspx
This is defining a lambda. You can read it "x goes to x.code equals code," and it means that given x, return the result of the given comparison.
It signals that the code is a lambda expression.
More info:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
They are related to lambda expressions.
You can read about Lambda Expressions here:
http://www.rvenables.com/2009/03/practical-introduction-to-lambda-expressions/

What is actually happening with IQueryable.Where()?

This is is returning a boolean based on whether or not there are some matching IDs.
from t in getAll
select new Result
{
...
bool DetailsAvailable =
(db.SaveTrackings.Where(s => s.BundleID == t.bundleID
&& s.UserID == t.userID)
.Count() > 0) ? true : false;
}
This is what I think understand: .Where() is returning all the entries with the matching IDs and then the .Count() is just seeing how many are there. I only feel like I half understand what we need s for.
I know what to expect from this code since it's been in use I just don't understand how it works and some of the documentation from MSDN is using some terminology that is confusing me.
All lambda expressions use the lambda
operator =>, which is read as "goes
to". The left side of the lambda
operator specifies the input
parameters (if any) and the right side
holds the expression or statement
block. The lambda expression x => x *
x is read "x goes to x times x."
So how am I suppose to understand what my code means based on this, .Where(s "goes to" s.BundleID == t.BundleID...) so what's happening here? What does "goes to" mean? Is it comparing every ID in s to everyone one available in t? How do I understand why it's called "goes to" and what exactly is happening?
And then it gets more confusing...
The => operator has the same
precedence as assignment (=) and is
right-associative.
Lambdas are used in method-based LINQ
queries as arguments to standard query
operator methods such as Where.
When you use method-based syntax to
call the Where method in the
Enumerable class (as you do in LINQ to
Objects and LINQ to XML) the parameter
is a delegate type System.Func. A lambda expression is the
most convenient way to create that
delegate.
What is a delegate type System.Func<T, TResult> and how is it created with this "goes to" operator?
I can't just use code because I know that it's working, I need to understand how/why.
Maybe it would help to see this function implemented by hand:
using System;
using System.Collections.Generic;
namespace CSharpSandbox
{
class Program
{
static IEnumerable<T> Where<T>(IEnumerable<T> input, Func<T, bool> predicate)
{
foreach (T item in input)
{
if (predicate(item))
yield return item;
}
}
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> evens = Where(numbers, n => n % 2 == 0);
foreach (int even in evens)
{
Console.WriteLine(even);
}
}
}
}
The construct name => someEvaluation creates an anonymous function consisting of the following parts:
name is simply the name of a parameter, its type is inferred from its usage. You need a name so you can refer to the argument passed in the function.
=> is the start of your anonymous functions body, the scope of the body is a single expression.
someEvaluation is the body of your anonymous function composed of a single expression.
In our case, Func<T, bool> defines a function which takes a single parameter of type T and returns an output of type bool. (If we had used Func<T, U, bool>, we'd take two inputs of type T and U and return a bool. The last type parameter in the Func definition is the return value.)
You can invoke an instance of Func exactly as you invoke any other function. If the func takes params, you pass them in as expected, your parameters are bound to the variable names you defined. When you invoke the function, control flow will jump inside your function and evaluate its results.
In principle, you don't need to create a Func anonymously. You can pass in any function which has a compatible type signature, such as:
static bool IsEven(int n)
{
return n % 2 == 0;
}
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> evens = Where(numbers, IsEven);
foreach (int even in evens)
{
Console.WriteLine(even);
}
}
This program produces the same output. In fact, behind the scenes, the syntax name => expression is syntax sugar; when it gets compiled, C# will produce a produce a private function with a hidden name and convert it to the format above.
If it helps, think of s as a variable of type SaveTracking. It's iterating over each s in your collection/table, and testing the value of its BundleID.
The t is same idea - it's like it's iterating through all the return collection from the getAll.
It's like the SQL pseudocode:
SELECT * FROM SaveTracking INNER JOIN GetAll
ON BundleID AND UserID
For a deeper technical description of what's going on with lambda expressions, check out Jon Skeet's book C# In Depth. Chapter 9 , p 230. I found this book very helpful.
Lambda expressions are just a way to shorten the code but it does exactly the same things as declaring a method that corresponds to the delegate type System.Func<T, TResult>
I believe that C# converts your lamba to a method in the background when you compile and it looks like this :
bool LambdaExpression(YourType s)
{
return s.BundleID == t.bundleID && s.UserID == t.userID;
}

Lambda to Expression tree conversion

I will keep it really simple,
How do I get expression tree out of lambda??
or from query expression ?
You must assign the lambda to a different type:
// Gives you a delegate:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => x * 2;
The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<> type, you can't get the expression tree back.
Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>> in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...> or other delegate type, all you have is a bunch of IL instructions.
If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecil library, which provides advanced IL manipulation support and could save you quite some time.
Just to expand on Konrad's answer, and to correct Pierre, you can still generate an Expression from an IL-compiled lambda, though it's not terribly elegant. Augmenting Konrad's example:
// Gives you a lambda:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);

Categories

Resources