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

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

Related

How to correctly read the method signature of the .Any function in C#

I really enjoy using the aggregate functions that C# provides such as .Any(), but I struggle to understand what my options are just looking from the method signature:
Can someone help me better understand the meanings of (Func predicate)? I know that I normally use a lamda fucntion here. But, how that translates back into whatever Func is, I don't understand.
(extension) bool IEnumerable<string>.Any<string>(Func<string, bool> predicate)(+ 1 overload)
Determines whether any element of a sequence satisfies a condition.
Exceptions:
ArgumentNullException
Means:
You can call this as an extension method.
On an IEnumerable<string>, that is something you can iterate on that gives you string. string is type that holds text.
The name of the method is Any
It has a type argument, which is set to string. You probably can call this on a IEnumerable<T> where T is something other than string.
It takes a Func<string, bool> predicate, that is a delegate to a function that takes a string as input parameter and returns a bool.
There is another overload of the method, which takes different arguments.
The method documentation says it "Determines whether any element of a sequence satisfies a condition." We can presume it goes over the IEnumerable<string> calls the Func<string, bool> passing the string from the IEnumerable<string> passing each value, and returns whether or not it got true for any one of them.
The method is documented to throw an ArgumentNullException, presumubly if you pass a null.
If we look online for it, we find in the official documentation Enumerable.Any. There we can see the other overload and also some examples.
Here is one:
Pet[] pets =
{ new Pet { Name="Barley", Age=8, Vaccinated=true },
new Pet { Name="Boots", Age=4, Vaccinated=false },
new Pet { Name="Whiskers", Age=1, Vaccinated=false } };
// Determine whether any pets over age 1 are also unvaccinated.
bool unvaccinated =
pets.Any(p => p.Age > 1 && p.Vaccinated == false);
We see an array of Pet, and we call Any on it. Thus, in this case the type argument is Pet instead of string, given that an array of Pet is a thing over which you can iterate and it gives you elements of type Pet... I'm saying that an array of Pet is an IEnumerable<Pet>... and thus we are calling Any<Pet>.
We observe that the parameter is a lambda expression: p => p.Age > 1 && p.Vaccinated == false
This lambda represents an anonymous function that takes an argument p. Since we know that we are using Any<Pet>, and we know that Any<Pet> wants a delegate to a function that takes a Pet and returns bool, we know that p is a Pet.
The anonymous function takes the Pet p compares the property Age with 1 and the property Vaccinated with false, and return true if Age is greater than 1 and Vaccinated is false.
Looking at the values in the array, we can see that the second item (the one of Name "Boots") has Age greater than 1 and Vaccinated is false. Thus, the anonymous function should return true for that Pet.
And given that Any return true if the predicate (the anonymous funciton) was true for any of the elements, we expect Any to return true in this case. The description of the example and expected output in the official documentation confirms this.
If we still have the doubt, we can, of course, try running the code: code on SharpLab. The expected output is "There are unvaccinated animals over age one.".
If you want to go one step deeper, you can search the reference implementation of Enumerable.Any.
If you know where to look, you can get the .NET Core source for Enumerable.Any, Not guaranteed to stay there, refectoring could put it somewhere else.
You may also be interested in the documentation about extension methods.
See also What is Func, how and when is it used.
But, how that translates back into whatever Func is?
Well, first we need to know what Func is.
Let's see how Func is declared:
public delegate TResult Func<in T,out TResult>(T arg);
We can see that Func is a delegate. If you don't know what a delegate is, there are wonder pages out there that tell you about them: 1, 2, 3.
How is related to the lambda expression you pass in?
The declaration says that Func is a delegate that takes a parameter of type T, and returns a TResult. From the signature of Any, we can see that T is string while TResult is bool in this particular case.
This means that you can convert a lambda expression, (or a method group,) that takes a string as a parameter and returns bool to an instance of Func<string, bool>.
Let's say you call Any like this:
something.Any(x => x.Length > 10)
From the parameter type, the compiler infers that the lambda expression must take a string, so the type of x must be string. And the lambda expression must also return a bool, which it does, so we're good! The lambda expression is converted to an instance of Func<string, bool>.

how to change OrderBy direction of IQueryable

I have some function (X) which return IQueryable with "OrderBy(x => x.Name)".
I want to use X function in new code, but in this code there is parameter which determine the order (asc/desc).
I prefer not to change (X) since it used in multiple places already.
there is option to get X(), then cancel it's "OrderBy", and apply new order?
(now it throws exception, since it is like Y.OrderBy(a => a.Name).OrderByDescending(a => a.Name))
"A column has been specified more than once in the order by list. Columns in the order by list must be unique.\r\nStatement(s) could not be prepared."
use
public void x(string order = string.empty)
{
Y.OrderBy(a => a.Name);
if (order == "desc")
{
Y = Y.Reverse();
}
}
I've tried to wiggle Expression object of IOrderedQueryable that your method is actually returning (am I wrong?) but so far no luck, and I can't see the option to manipulate System.Linq.Expression or System.Linq.EnumerableQuery easy enough to use it instead of changing X() method.
IMHO, you should choose from:
create somes kind of wrapper method using the Reverse() (#Eric Lizotte answer) or OrderByDescending() - it will be less time consuming I guess but for grouping, filtering etc. you will have to create brand new function.
remove OrderBy() from X() function body, and modify your old code - returning non-ordered result will give you more flexibility and opportunity to do what you want to do with the result via linq expressions in each scenario that you'll came across.
Can you clarify for me if you're talking about "function" you have in mind a sql function that is mapped via ORM (eg. Entity Framework) in your application or just a ordinary method which is using your custom provider to return IQueryable?

Struggling to understand Lambda expressions with LINQ [closed]

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.

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

Question about linq query format

var q = (dc.tblHelpCentreQuestions.Where(c => c.userID == UserID));
q.OrderByDescending(c => c.dateSubmitted);
I'm just getting used to Linq, and I'm sorting my records by date submitted descending, but could someone explain to me why I have to do c => c.dateSubmitted and not just pass in tblHelpCentreQuestions.dateSubmitted? What does the c=> do and why is it needed?
It is a lambda expression. Read about them here.
Also note that OrderByDescending returns a new IEnumerable, it does not do an in-place sort. You will want to read about Linq basics here.
q = tblHelpCentreQuestions is enumerable. It does not have dateSubmitted property. Its elements have that property. C stands exactly for that element
the c=>c.dateSubmitted is a lambda expression, they are used a lot with Linq. In this case, it's kind of a selector. it defines which property of your class to order by. tblHelpCentreQuestions.dateSubmitted in the other hand is just a "value", it doesn't give info about the property.
Put simply, a lambda expression is an anonymous method. a method needs parameters, that's what the c=> is for. if you have a method that takes two arguments (say, sender and args), you would have something like (sender, args)=>. There are Expression Lambdas, which have one expression as their body (as is the case with your example), and Statement Lambdas which can have more than one instruction (or statement), and thus need a block to delimit it. (sender, args)=>{ ... }. It may or may not have a return value.
Hope this helps :)

Categories