Lambda Example in C# - c#

I am still learning some of the features of C# 3.0 and want to know if the following can be reduced to a lambda expression.
var SomeObject = Combo.EditValue;
var ObjectProperty = SomeObject.Property;
To obtain ObjectProperty from the combo.editvalue in a single line?
Also, if you can provide me with any good references to Lambda expressions, it would be appreciated.
EDIT: Ok, the answers posted are great, it appears that the example does not need a Lambda to satisfy the solution. I will take a look at the reference links though.

You don't really need lambdas to do that all you would need to do is
var ObjectProperty = Combo.EditValue.Property;
I'm not sure a lambda is going to make that any more readable for you.
Here are some books you might want to take a look at to learn Lambdas in more detail, and also why you'd use them:
More Effective C#
C# In Depth
MSDN Reference

Combining those into one line, you run the risk of a NullReferenceException, by checking the Property property on EditValue. :) But, here is a really great tutorial on C# 3.0 and functional programming.

this does not appear to need a lambda.
Can't you just use
var ObjectProperty = Combo.EditValue.Property
As far as lambda references try 101 LINQ Examples for starters.

Related

Trying to use Visual Studio better! How would I find help on the sort method?

I am reading through a book and it gives an example of the Sort Method along with a Lambda query.
An example is {Product.Sort( (x,y) => x.Name.CompareTo(y.Name) );
This really took me a while to understand as I did not understand how .Sort was dealing with the two inputs on the lambda.
I tried clicking on Sort and pressing F1 for help, but, it didn't give anything, that made any sense to me.
Perhaps I am just not good enough to understand those examples, but, I just could not work out how this was working until I changed the Lambda to x,y,z which gave the error Error Delegate 'System.Comparison<ConsoleApplication1.Product>' does not take 3 arguments
Which made a lot more sense to me... Anyway, after a while of looking around, I am confident that I understand the Sort method, but, it took me a lot longer than I am happy with.
From people who are much better than me - given a situation like this, how would you search for help?
By typing Shift+SpaceI was also able to produce the following:
However, I am just wondering, as a C# learner, how can I attribute this to requiring a Lambda with two inputs?
It does not require a lambda. It requires only a delegate of type Comparison. For example, there may be a method:
int CompareProductNames(Product x, Product y)
{
return x.Name.CompareTo(y.Name);
}
and then you could call Sort like this:
productList.Sort(CompareProductNames);
Comparison<T> is a delegate that takes two parameters of type T and returns an int.
It sounds like you don't need an explanation of what's going on but instead how to figure it out. Hover your mouse over the Sort part and you'll see the specific overload being called. In this case its Sort(Comparison<Product>)) which maps to Sort(Comparison(T))
One of the approaches is to check out the Comparison documentation. It's a delegate, e.g. pointer to a function, that takes two arguments of type T and returns integer value. T type is declare in Sort<T> method of the List<T> class, so T here is a Product. Lambda expressions is just a shortcut for this function.
The main point is to understand that this code is just an equivalent of:
public void DoSort()
{
list.Sort(Compare); //Pass method as a Comparison<Product>
}
public int Compare(Product x, Product y)
{
return x.Name.CompareTo(y.Name);
}
Look up List<T>.Sort on Google and then Google it's arguments if you don't understand. That's the way most dev's work these days.
I, for one, could not write code without the help of Google and sites like SO itself.
Also, you have to understand how delegates work, in the case of sort, as the lambda is really an anonymous method that is passed to the delegate. The input's are captured by the lambda, are arguments to the delegate.
It might be easier to understand the MSDN doc that comes up with F1 if you know that a lambda evaluates to a single delegate value. The MSDN doc shows two overloads for Sort with a single argument; clicking on the argument type of these will show that Comparison is a delegate taking two arguments.
You do have to drill in a few steps in the MSDN doc to find the information you are looking for.

when to use or not Lambda Expressions

I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.
Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language.
Other factors against are the cost using reflection by lambda and that not friendly to debugging.
I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions.
(this is not the better example, but let's say it was the trigger)
I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = delegate { return null;}
Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = () => null;
At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.
There are somewhat two questions here.
First, as for your example, using a lambda vs. using the anonymous delegate syntax. The generated code by the compiler will be identical, so it does not come down to a performance difference, but rather a readability difference.
Personally, I find the lambda syntax easy to follow. I find that the lambda syntax is almost always cleaner, more concise, and more understandable than the anonymous delegate syntax, so I prefer it nearly always.
As for using lambda expressions throughout the code - Personally, I am a fairly heavy user of them. I find that they often make life much easier than having lots of methods defined. If a piece of code is not going to be reused by any other methods (it will only be called and exist in one place), I will use a lambda to express it.
If a piece of code is going to be used more than once, it should be pulled out into a (non-anonymous) method. Also, if a piece of code is something that could and should be tested, I tend to make a method for it, since that eases testability.

Extract Expression Tree From Action

I'm just starting out playing around with Linq Expressions and I've hit a wall. I need to create an Expression Tree from an Action. Unfortunetly I can't get the Action as an Expression, this is basically what I've got to work with:
public void Something(Action action){}
I need access to the body of the Action to extract variables and values.
An Action is not an Expression; it is simply a delegate (that might have been an expression at some point, might have been a lambda, and might not have been either).
To make this workable, you would need to refactor to:
public void Something(Expression<Action> action) {...}
Also, C# 3.0 / .NET 3.5 lambda expressions don't work very well for Action-type expressions. You are very limited in what you can express. Func-type expressions work better. In .NET 4.0 (CTP) there is much more flexibility here, although it still isn't clear what the language (C# 4.0) will offer by way of lambdas.
Basically, I'm not sure that you can (conveniently) do what you hope using Expression.

Should I *always* favour implictly typed local variables in C# 3.0?

Resharper certainly thinks so, and out of the box it will nag you to convert
Dooberry dooberry = new Dooberry();
to
var dooberry = new Dooberry();
Is that really considered the best style?
It's of course a matter of style, but I agree with Dare: C# 3.0 Implicit Type Declarations: To var or not to var?. I think using var instead of an explicit type makes your code less readable.In the following code:
var result = GetUserID();
What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.
Jeff wrote a post on this, saying he favors var. But that guy's crazy!
I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.
I use it only when it's clearly obvious what var is.
clear to me:
XmlNodeList itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
not clear to me:
var itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
The best summary of the answer I've seen to this is Eric Lippert's comment, which essentially says you should use the concrete type if it's important what the type is, but not to otherwise. Essentially type information should be reserved for places where the type is important.
The standard at my company is to use var everywhere, which we came to after reading various recommendations and then spending some time trying it out to see whether the lack of annotated type information was a help or a hindrance. We felt it was a help.
Most of the recommendations people have linked to (e.g. Dare's one) are recommendations made by people who have never tried coding using var instead of the concrete type. This makes the recommendations all but worthless because they aren't speaking from experience, they're merely extrapolating.
The best advice I can give you is to try it for yourself, and see what works for you and your team.
#jongalloway - var doesn't necessarily make your code more unreadable.
var myvariable = DateTime.Now
DateTime myvariable = DateTime.Now;
The first is just as readable as the second and requires less work
var myvariable = ResultFromMethod();
here, you have a point, var could make the code less readable. I like var because if I change a decimal to a double, I don't have to go change it in a bunch of places (and don't say refactor, sometimes I forget, just let me var!)
EDIT: just read the article, I agree. lol.
There was a good discussion on this # Coding Horror
Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.
I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to preference. Whatever you think is more readable. I prefer var when the type is defined on the right side because it is terser. When I'm assigning a variable from a method call, I use the explicit type declaration.
It only make sense, when you don't know the type in advance.
In C# 9.0 there is a new way to initialize a class by Target-typed new expressions.
You can initialize the class like this:
Dooberry dooberry = new();
Personally, I like it more than using a var and it is more readable for me.
Regarding calling a method I think it is up to you. Personally, I prefer to specify the type because I think it is more readable this way:
Dooberry dooberry = GetDooberry();
In some cases, it is very clear what the type is, in this case, I use var:
var now = DateTime.Now;
One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterward. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.
Good tools let you have the best of both worlds.
John.
"Best style" is subjective and varies depending on context.
Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.
Other times, using the full class name is more helpful as it documents the code better than 'var' does.
I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".
Cheers!
I'm seeing a pattern for stackoverflow
success: dig up old CodingHorror posts
and (Jeopardy style) phrase them in
terms of a question.
I plead innocent! But you're right, this seemed to be a relatively popular little question.
There's a really good MSDN article on this topic and it outlines some cases where you can't use var:
The following restrictions apply to implicitly-typed variable declarations:
var can only be used when a local variable is declared and initialized
in the same statement; the variable
cannot be initialized to null, or to a
method group or an anonymous function.
var cannot be used on fields at class scope.
Variables declared by using var cannot be used in the initialization
expression. In other words, this
expression is legal: int i = (i = 20);
but this expression produces a
compile-time error: var i = (i = 20);
Multiple implicitly-typed variables cannot be initialized in the same
statement.
If a type named var is in scope, then the var keyword will resolve to
that type name and will not be treated
as part of an implicitly typed local
variable declaration.
I would recommend checking it out to understand the full implications of using var in your code.
No not always but I would go as far as to say a lot of the time. Type declarations aren't much more useful than Hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.
Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long Generic<OtherGeneric< T,U,V>, Dictionary< X, Y>>>

What is appliance and how to use lambda expressions? [duplicate]

This question already has answers here:
C# Lambda expressions: Why should I use them?
(17 answers)
Closed 8 years ago.
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?
They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?
Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.
: are lambda expressions useful for anything other than querying
Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'.
So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.)
An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.
This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.
Lambdas bring functional programing to C#.
They are anonymous functions that can be passed as values to certain other functions. Used most in LINQ.
Here is a contrived example:
List<int> myInts = GetAll();
IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);
Now when you foreach through evenNumbers the lamda
x=> x % 2 == 0
is then applied as a filter to myInts.
They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops.
Here's a simple example of something cool you can do with lambdas:
List<int> myList = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
myList.RemoveAll(x => x > 5);
//myList now == {1,2,3,4,5}
The RemoveAll method takes a predicate(a delegate that takes argurments and returns a bool), any that match it get removed. Using a lambda expression makes it simpler than actually declaring the predicate.

Categories