Struggling to understand Lambda expressions with LINQ [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I'm very new to this and I can't get my head around the examples I am seeing online. I have been trying to use a lambda statement to sort a list like with the example code I found online:
public void Linq29()
{
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords = words.OrderBy(word => word.Length);
Log.WriteLine("The sorted list of words (by length):");
foreach (var w in sortedWords)
{
Log.WriteLine(w);
}
}
I've read a lot of information about how it works, but I can't just get my head around how 'word' can start referring to the items in the list of words.
Can anyone help put this in very simple terms so I can start understanding it.
Thanks.

The line
var sortedWords = words.OrderBy(word => word.Length);
uses a so-called lambda expression, which is a concept separate from Linq. The same functionality could be implemented by using a separate function
public static int function(string word)
{
return word.Length;
}
and using it as follows.
var sortedWords = words.OrderBy(function);
the lambda expression word => word.Length is much shorter and defines a similar function inline. In this formulattion, word (on the left-hand side) defines a name for the argument.

I've read a lot of information about how it works, but I can't just get my head around how 'word' can start referring to the items in the list of words.
OrderBy is an extension method for IEnumerable<T>, which is what your list of words is.
OrderBy can enumerate over the elements itself because it knows words is of type IEnumberable<T>.
OrderBy however requires a "keySelector" to let it know what you want to order by. The keySelector is a delegate type. This should take a parameter and return something. (MSDN calls it "A function to extract a key from an element.")
word => word.Length
word is the parameter, and word.Length is the method body.
So you are taking the word, and then returning its length.

I'm going to take a stab at this using the concept that helped me get my head round lambdas in the first place. Lets look at the lambda:
word => word.Length
This is short hand for (word) => word.Length which in turn is shorthand for (word) => {return word.Length;}
this lambda is in turn short hand for an anonymous function with type inference, the below is therefore only pseudo code:
delegate(var word) {return word.Length;}
The compiler CAN infer the type of var, thus in Your example this is short hand for:
delegate(string word) {return word.Length;}
which is in turn shorthand for (again the output type is infered so this is specific to your example):
static class [compilerInventMeAClassNamePlease]
{
static int [compilerInventMeAMethodNamePlease] (string word)
{
return word.Length;
}
}
...
[a call to][compilerInventMeAMethodNamePlease]
These classes and method really are made by the compiler.
Thus a lambda is a way to inline create a anonymous class / method which you have not given a name and define it. Everything on the left of the => is signature. While you are getting comfortable with it you might find it easier to write them, at least initially, in the long-hand format:
(string word, int multiply) => { return word.Length * multiply; }
Please note the class generated by the lambda may not be static but a real instance class with its own instance fields, this is due to a concept called a closure which is the next thing to investigate when you are comfortable with lambdas

Think of "word" as being the parameter you would pass to a function that would sort the elements.
What is it that you need to sort the elements of a sequence ? First of all, you need a criteria that establishes, for any given element in the sequence, whether it should preceed or not the subsequent element. Usually you will define it via a function, because a function can take any number of elements/parameters and "state"/return "one single affirmation/thing" regarding the input elements it received. In our case, a sort function, upon receiving two elements, will say whether the 1st should preceed or not the 2nd when ordering the elements.
After you have such criteria defined, you would need to go over each element and, based on a sorting criteria (described above) check if the current element should preceed or not the next one in orderning the sequence.
That's why the framework gives you a Sort method that receives a function. It will do the work of looping over every sequence element for you and check the result of the sorting criteria, and based on that, order the elements.

how 'word' can start referring to the items in the list of words
Check the method signature which is:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
So it's an extension method for the IEnumerable<TSource>. It expects a parameter of type Func<TSource, TKey> which in itself is a delegate, this is why you provide an anonymous function as the parameter: (word) => { word.Length; }. The program knows that word is the same type as an item of your collection words because word is a parameter of type TSource, which is of the same type as the this IEnumerable<TSource> source that the method OrderBy() extends from.

Related

Can Anybody Explain to Me What This Line Does in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have don't understand the <...> syntax, is this is function?
Could anyone explain me this line of code?
ApplyPropertyChange<AgreementTransaction, int>(ref _agreementId, o => o.AgreementId, value);
Based on the named of the method (ApplyPropertyChange) and the type of arguments, that looks like a setter for an element in a set of elements. The <> use is to pass the type of element, in this case it is an AgreementTransaction; the second argument of type int is most likely what to expect value to be or the result of the Func to be.
ApplyPropertyChange(ref _agreementId, o => o.AgreementId, value);
It looks like it is taking the set of elements, finding the element in the set by using its AgreementId, and then setting the value shown.
It could in some ways be rewritten like this at a basic level.
foreach(AgreementTransaction el in setOfElements)
{
if( (int)el.AgreementId == _agreementId )
{
el.AgreementId = value;
}
}
The Func<> passed in is referred to as a predicate. It is essentially a delegate which will project an AgreementTransaction into an int.
Think of it like this:
AgreementTransactions.Select( o => o.AgreementId );
or in a broader example:
List<AgreementTransaction> AgreementTransactions = someListOfThem;
List<int> result = new List<int>();
foreach(AgreementTransaction agree in AgreementTransactions)
{
result.Add(agree.AgreementId);
}
Overall, there is a lot more going on that I will not get into with regards to Lambda expressions, Func declarations, and delegates. You can read more on that from MSDN: https://msdn.microsoft.com/en-us/library/bb397687.aspx
This syntax:
o => o.AgreementId
is the use of the lambda operator.
Specifically, this creates an anonymous function that takes one parameter, named o, and where the body is simply return o.AgreementId.
So this:
o => o.AgreementId
is short-hand for this:
delegate(var o)
{
return o.AgreementId;
}
however you can't really specify var o like that, but for the lambda operator the compiler can infer the right type for o depending on the delegate the function is fitted into, and this is where you need to go to the ApplyPropertyChange method, most likely it looks something like this:
public void ApplyPropertyChange<T1,T2>(ref T2 value, Func<T1,T2> getValue, T1 inputValue)
in which case T1 and T2 are inferred from o.AgreementId and ref _agreementId.
=> Is the lambda operator. Some people say that you pronounce it as "goes to". It is a shortcut for a delegate.
Maybe the sentence above holds several new concepts for you. The idea behind a delegate is that you don't give the value as a parameter of a function, but a function. In fact the parameter is a value, but the value is not an integer, or an object; it is of a function type.
If you call a function like F(x) and you you give a value 4 as a parameter, you'll tell this function that whenever it sees the letter X it should use the value 4.
The same is with delegate. If you have a function with a delegate D as a parameter and you call it with the parameter Sin(x) you say to the function that whenever it uses a call to D it should call Sin(x).
The traditional way of using delegates involved quite some typing. With the introduction of lambda expression this was made much easier.
The lambda expression is heavily used in Linq. Whenever you need to do things with sequences like arrays / lists / collections / sets, whatever, and you would normally use foreach Linq will make live easier for you.
For example, let's say you'll have a sequence of Persons. I use here the term sequence, because I don't care whether it is an array, a list, a set, a collection, whatever. The only think I demand from it is that I can ask for the first element and for the next element in the sequence until there are no more elements. In short: I demand that the sequence is Enumerable.
Suppose from this sequence I only want the Persons with a value for the FirstName property "John". For this the static function Enumerable.Where is used. The result is an IEnumerable of the same type as my original sequence:
IEnumerable<Person> personsNamedJohn = Persons
.Where(p => p.FirstName == "John");
Here you'll see the =>. You could phrase it as:
From the sequence Persons, take each person (let's call it p), where p.FirstName == "John".
I quite often keep it readable by giving my sequences a plural identifier (Persons) and instead of p I write the singular identifier:
IEnumerable<Person> personsNamedJohn = Persons
.Where(person => person.FirstName == "John");
IEnumerable<Shape> circles = Shapes
.Where(shape => shape.ShapeType == Shape.Circle);
There are a lot of other Linq functions where you use lambda. We saw that the function where gives you the elements of the sequence that match the predicate. The function Select will use each item of the sequence to create another item.
IEnumerable<Address> addressesOfPersonsNamedJohn = Persons
.Where(person => person.FirstName == "John")
.Select(person => new Address(person.Street, person.City, person.ZIP));
This is: from all Persons, take only the persons whith a firstname of "John", and from each of these persons take the Street, City and ZIP property as parameters for the constructor of an Address object. The result is a sequence of Addresses.
In the beginning I found the use of the lambda operator quite confusing, but once I understood it, it became very useful. Whenever I would write foreach, I find that it can quite often be written much shorter and easier to understand if I use a Linq statement with a lambda expression.
The standard linq operatores was a good starting point for me to understand linq, delegates and lambda

Understand linq syntax [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am really confused to understand its internal working
This is LINQ syntax
string[] test = new test[] { "abc", "", "cd", "", "aa" };
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
I am confused about where syntax how it manages. is it put all array in x? if yes then how it manage x null value?
or
if not then test array values put one by one in the x?
You should consider the rest of the answers, they are pretty accurate, what I want to show you and maybe this will help you to understand the syntax is that this kind of query can actually be represented in a query syntax like this:
string[] test=new test[]{"abc","","cd","","aa"};
// this is the equivalent to your code
// added explicit type to make it clearer, it's optional
var a = from (string)x in test
where !string.IsNullOrEmpty(x)
select x;
if you are familiar with SQL, you will find this syntax easier to read, even when you do not know it, this syntax is cleaner.
When the code is compiled, this query syntax is automatically translated to the C# method syntax, in order to generate the IL, so if you dissasmbly a DLL you will see the method syntax instead of the query syntax
A brief explanation about this code:
As you can see an x variable was declared and it's of type string. Why? because your array is an array of strings
The in test indicates the source IEnumerable<> to iterate - your array in this case
The where is pretty explanatory, it simply selects all not null strings from your array
And finally the selects which actually is a projection of the data.
And all this is equivalent to your code
Now you might be asking yourself... When should I use one syntax or the other? Well they are equivalent but the query syntax operators are limited which means that most of the operations are done with method syntax instead of query syntax. What I always do is try to write the code easier to read some code is easier to understand if it is written with a query syntax.
About the method syntax, the x => ... syntax is known as lambda expression, they might look weird if it is the first time you are working with them but you will love them eventually.
Basically lambdas are shortcuts to delegates, so what you are doing with:
x => !string.IsNullOrEmpty(x)
You are creating an anonymous method and the method is being assigned to the delegate parameter. The x represents the string variable.
This topic is really extensive to try to explain it here, but I hope this has given you an idea of what's behind.
Btw you can combine the syntax's like this:
// this is the equivalent to your code
// added explicit type to make it clearer, it's optional
var a = (from (string)x in test
where !string.IsNullOrEmpty(x)
select x).ToArray();
If you google LINQ is like googling porm lol the web is plagued with LINQ articles, samples, etc.
A good point of start would be the 101 samples from Microsoft
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
EDIT
I will try to emulate the Where method so you can have a better example of the lambda expression
// this is basically the declaration of one overload of the Where method
// the this in the parameter declaration, indicates this is an extension method which will be available to all IEnumerable<> objects
// the Func<T, bool> is the interesting part, it is basically a delegate (as a reminder, the last parameter of the Func object indicates the type that must be returned, in this case is a bool)
// the delegate is simply a pointer to a function
public IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
...some logic
... yielding back the reuslts
foreach(var r in res)
{
// here is the delegate in action
if(predicate(r))
yield return r;
}
}
As you can see the delegate was called as a function (delegates are pointer to functions)
Butt what function??? the one you declared in your code
x => !string.IsNullOrEmpty(x) and the x indicates the parameter passed back from the Where method to the external code, where you can inspect it and use it to filter your results
The x => is an abbreviation to declare a delegate
!string.IsNullOrEmpty(x) this is the body of your anonymous method and as you can see it fulfills the requirements of the Func<T, bool> it is returning a bool (the predicate to filter the elements of the array) and as a parameter, it received the generic T which in this case is a string from your array
Another way to declare the lambda expression is:
test = test.Where(
(string) x =>
{
return !string.IsNullOrEmpty(x)
})
.ToArray();
With this syntax is easy to show that they are actually methods (anonymous methods)
we can take the statement apart and examine the pieces one at a time
x => !string.IsNullOrEmpty(x) is basically defining a function like the below
bool Filter(string x){
return !string.IsNullOrEmpty(x)
}
and creates a Predicate based on that function. A predicate is just a delegate - a function you can pass in a variable.
.Where is an extension method that for simplicity could be defined
IEnumerable<T> Where<T>(this IEnumerable<T> sequence,Predicate<T> pred){
foreach(var elem in sequence){
if(pred(elem)){
yield return elem;
}
}
}
had you defined the function as Filter is defined above instead of using a lambda your statement would look like this
test = test.Where(Filter).ToArray();
so by calling this extension method on your array and passing the above predicate you will iterate over all elements in the array and return all those elements that matches the predicate (Ie. those that are neither null nor have the value of the empty string)
Finally you call the extension method .ToArray() which turns what .Where returned (an IEnumerable<string>) into an array
EDIT
Read this article you will surely get good idea about that you have writtnen......
C# 3.0 New Language Features (Part 1)
C# 3.0 New Language Features (Part 2)
it's from of extenstion method + lambda experssion part of C# 3.0
here in this code
test=test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
where - is a extesion method
x => !string.IsNullOrEmpty(x) - is lambda expresion , which is replacement of anonymous function
this whole function check the each element of array ...i.e the lamdaba expression check the each element of the array satisfy the conditon which is written and than finally retuns array of those element which satisfy the condition

Trivial lambdas in LINQ

Edit: Despite the upvotes I don't think this is a good question anymore (see various comments). Sorry for the wasted space, but unfortunately I lack the rep to delete my own post.
Is there a better way of creating a lambda (or perhaps a predicate or expression that is not a lambda) that returns either 1) The sole argument unchanged or 2) a constant value? I encounter this occasionally when using LINQ where a basic LINQ extension method requires a Func<x,y> but I only need the input argument or a constant.
In a two year-old question Jon Skeet asserted that there is no reduction for the identity function (see LINQ identity function?). Is same true of a constant expression? Has (or will) anything chang(ed) with .NET 4.5 or C#5?
you don't need to specify a predicate for the Count method
.Count()
If you were looking for a kind of lambda constant, a regular method would be the closest candidate. Let us say a Func<string,bool> is required and you want it to return it true in any case. Instead of writing collection.SomeLinqMethod(s => true) you could create a static class with appropriate methods
public static class Expressions
{
public static bool True(string s)
{
return true;
}
}
Then you would write
var result = collection.SomeLinqMethod(Expressions.True);
You could also have generic methods
public static bool True<T>(T item)
{
return true;
}

Why does this MSDN example for Func<> delegate have a superfluous Select() call?

The MSDN gives this code example in the article on the Func Generic Delegate:
Func<String, int, bool> predicate = ( str, index) => str.Length == index;
String[] words = { "orange", "apple", "Article", "elephant", "star", "and" };
IEnumerable<String> aWords = words.Where(predicate).Select(str => str);
foreach (String word in aWords)
Console.WriteLine(word);
I understand what all this is doing. What I don't understand is the
Select(str => str)
bit. Surely that's not needed? If you leave it out and just have
IEnumerable<String> aWords = words.Where(predicate);
then you still get an IEnumerable back that contains the same results, and the code prints the same thing.
Am I missing something, or is the example misleading?
The Select is indeed redundant.
I suspect that this example may have been "translated" from the query comprehension syntax, as in:
IEnumerable<String> aWords =
from w in words
where (...)
select w;
When using this syntax, you have to select at the end, it's just how the compiler works. When using the Where extension method, however, it's completely unnecessary unless you actually need to do a separate projection.
Or, maybe it's just a mistake. The MSDN writers aren't infallible!
No it's not needed.
Such a construct could be used if you wanted to force a sequence to be lazily evaluated i.e. to prevent casting. If you had a method that returned a List<T> but declared an IEnumerable<T> return type then a client could cast the return type and manipulate the underlying list directly. Obviously this is a very bad idea, but a class could protect its state by applying an identity select such as the one used in this example:
public IEnumerable<T> Items
{
get { return privateList.Select(i => i); }
}
Indeed, it's not needed, there's a feedback button on bottom of msdn page. Tell them the .Select is not needed. The mere fact that the Select clause is just:
Select(str => str)
It receives string and outputs the same string
You have a very strange link there. This topic is not in TOC, and it has the following at the top:
"[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]"
The first line also looks like writer's comment to himself/herself.
And since VS 2010 and .NET 4.0 just released, I guess, this is some kind of broken topic that hasn't been deleted/replaced in time.
I think, the correct URL now for this content is this: http://msdn.microsoft.com/en-us/library/bb534303.aspx
By the way, how did you get your URL? Was it through MSDN search or something else?

Adding functonality to Linq-to-SQL objects to perform common selections

In a previous question I asked how to make "Computed properties" in a linq to sql object. The answer supplied there was sufficient for that specific case but now I've hit a similar snag in another case.
I have a database with Items that have to pass through a number of Steps. I want to have a function in my database that retrieves the Current step of the item that I can then build on. For example:
var x = db.Items.Where(item => item.Steps.CurrentStep().Completed == null);
The code to get the current step is:
Steps.OrderByDescending(step => step.Created).First();
So I tried to add an extension method to the EntitySet<Step> that returned a single Step like so:
public static OrderFlowItemStep CurrentStep(this EntitySet<OrderFlowItemStep> steps)
{
return steps.OrderByDescending(o => o.Created).First();
}
But when I try to execute the query at the top I get an error saying that the CurrentStep() function has no translation to SQL. Is there a way to add this functionality to Linq-to-SQL in any way or do I have to manually write the query every time? I tried to write the entire query out first but it's very long and if I ever change the way to get the active step of an item I have to go over all the code again.
I'm guessing that the CurrentStep() method has to return a Linq expression of some kind but I'm stuck as to how to implement it.
The problem is that CurrentStep is a normal method. Hence, the Expression contains a call to that method, and naturally SQL cannot execute arbitrary .NET methods.
You will need to represent the code as an Expression. I have one in depth example here: http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx
Unfortunately, the C# 3.0 compiler has a huge omission and you cannot generate calls to Expressions. (i.e., you can't write "x => MyExpression(x)"). Working around it either requires you to write the Expression manually, or to use a delegate as a placeholder. Jomo Fisher has an interesting post about manipulating Expression trees in general.
Without actually having done it, the way I'd probably approach it is by making the CurrentStep function take the predicate you want to add ("Completed == null"). Then you can create a full Expression> predicate to hand off to Where. I'm lazy, so I'm going to do an example using String and Char (String contains Chars, just like Item contains Steps):
using System;
using System.Linq;
using System.Linq.Expressions;
class Program {
static void Main(string[] args) {
Console.WriteLine(StringPredicate(c => Char.IsDigit(c)));
var func = StringPredicate(c => Char.IsDigit(c)).Compile();
Console.WriteLine(func("h2ello"));
Console.WriteLine(func("2ello"));
}
public static Expression<Func<string,bool>> StringPredicate(Expression<Func<char,bool>> pred) {
Expression<Func<string, char>> get = s => s.First();
var p = Expression.Parameter(typeof(string), "s");
return Expression.Lambda<Func<string, bool>>(
Expression.Invoke(pred, Expression.Invoke(get, p)),
p);
}
}
So "func" is created by using StringPredicate to create an Expression. For the example, we compile it to execute it locally. In your case, you'd pass the whole predicate to "Where" so it gets translated to SQL.
The "get" expression is where you put your "extension" stuff (OrderByWhatever, First, etc.). This is then passed in to the predicate that's given to you.
Don't worry if it looks complicated; it sorta is at first. If you haven't done this kinda stuff before, it'll take a bit of time (the first time I did this kinda stuff, it took hours to get it right :|.. now it comes slightly easier). Also, as I mentioned, you can write a helper method to do this re-writing for you (so you don't directly need to use the Expression.Whatever methods), but I haven't seen any examples and haven't really needed it yet.
Check out my answer to "switch statement in linq" and see if that points you in the right direction...
The technique i demonstrate there is the one that got me past the scary "no translation to SQL" error.

Categories