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
Related
I found this sample of code on SO (can't remember from where :/) that allowed me to check for line code arguments when launching my application :
if (e.Args.Length == 0 || e.Args.Any("-show".Contains))
{
//show interface...
}
I just can't seem to understand how the "-show".Contains works.
And if there's any difference with a (classic) x => x.Contains('"-show") (except for the evident typing gain).
Works like a charm but I'd like to understand why, I feel like something big is hapening.
This:
.Any("-show".Contains)
is basically shorthand for this:
.Any(s => "-show".Contains(s))
The Any method takes a delegate as a parameter and you can create that delegate in a number of ways. The first snippet uses a method group while the second uses a Lambda.
It's not really accurate to say that the first is shorthand for the second because method groups predate Lambdas, but if you think in terms of Lambdas when calling LINQ methods like Any then it is effectively the case.
As #jmcilhiney already said, it shorthand for:
.Any(s => "-show".Contains(s))
Contains is a function accepting 1 parameter which is of type string (and returns a boolean). Any() in this case wants a function that needs 1 param which is a string and that returns a boolean. So rather than adding an extra lambda warapper s=>, you can directly return .Contains
In technical terms this is a:
Func<string, boolean> //1 param string, output: boolean
Note that this code matches any argument that is a part of -show
thus either of the following arguments do match!
-show
-s
sh
ow
h
w
// etc..
Any() expects a Func<TSource, bool> delegate. So any function that returns a bool and takes an argument that is of the same type as the elements of the collection (string in your case) can be applied. This can be an existing function, or a lambda expression.
The signature of String.Contains is
bool Contains(string s)
That's why you can pass it to Any()
The equivalent would be x => "-show".Contains(x) rather than what you've shown.
After that you'll realise that all you're doing by introducing the x based lambda is to create a function accepting a single string argument and returning a bool and wrapping a function that accepts a single string and returns a bool. There's no need for the wrapper.
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
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.
I know that this is Linq:
var _Results = from item in _List
where item.Value == 1
select item;
And I know this is Lambda:
var _Results = _List.Where(x => x.Value == 1);
Editor's note: the above is not merely Lambda, it is Linq using the "Method
Syntax" whose predicate is a Lambda. To be clear, both of the above
samples are Linq (my original post was incorrect, but I left the error
to illustrate the confusion prompting the question).
But is Linq a subset of Lambda or what?
Why are there two seemingly identical techs?
Is there a technical reason to choose one over the other?
This is LINQ (using query syntax):
var _Results = from item in _List
where item.Value == 1
select item;
This is also LINQ (using method syntax):
var _Results = _List.Where(x => x.Value == 1);
It's interesting to note that both of these flavors will end up producing the exact same code. The compiler offers you a service by allowing you to express your wishes in the manner that you prefer.
And this is a lambda:
x => x.Value == 1
When you choose to use method syntax, LINQ is almost always seen around lambda expressions. But LINQ and lambdas are two totally different things, both of which can be used by themselves.
Update: As svick rightly points out, LINQ with query syntax is also implemented using lambda expressions (as mentioned earlier, the compiler allows you to write in query syntax but effectively transforms it to method syntax behind your back). This is just piling on the fact that both flavors are totally equivalent and will behave the same way (e.g. lambda expressions may cause closures to be created).
Both are Linq. The second one is using Lambdas.
Lambdas are the inline method type things that you are passing as a parameter to the Where function in the second example.
The difference between those two syntaxes is purely syntactic. The second linq style using method calls is how it works under the hood. The first is meant to be more user friendly/easier and the compiler converts it to method calls behind the scenes. They should work the same for any given query though of course the compiler may choose a sligthly different interpretation of a complicated linq query than you would when converting to method style.
This msdn article may be of interest too: LINQ Query Syntax versus Method Syntax. Of particular relevance is: "In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax."
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.