Lambda Expressions common usage areas in c#
I know that Lambda Expressions is not just for LINQ. But what are the possible scenarios which we can use Lambda Expre开发者_StackOverflow社区ssion in? what is the code of these examples without Lambda Expression?
Let's say you have a list of Person
objects and want to make a Dictionary<int, string>
out of it to be able to look up person's name by his SSN or something.
With ToDictionary
method it's easy:
var dictionary = Persons.ToDictionary(p => p.SSN, p => p.Name);
The alternative is to create a dictionary and then use a foreach
loop:
var dictionary = new Dictionary<int, string>();
foreach (Person p in Persons) {
dictionary.Add(p.SSN, p.Name);
}
Which is kinda wordy and hides the intent.
You can use ToDictionary
but without lambda expressions:
var dictionary = Persons.ToDictionary(GetPersonKey, GetPersonValue);
//....
int GetPersonKey(Person p) {
return p.SSN;
}
string GetPersonValue(Person p) {
return p.Name;
}
which is obviously not so concise.
You could go with anonymous delegates:
var dictionary = Persons.ToDictionary(delegate(Person p) { return p.SSN; },
delegate(Person p) { return p.Name; });
but it doesn't compare with lambda expressions in conciseness.
I wouldn't want to use any LINQ extension methods if lambda expressions weren't implemented in the language because it would requite a lot of unnecessary code.
When dealing with anonymous methods, I found that I learned a lot from simply using ReSharper.
The suggestions regarding lambda expressions and anonymous methods from ReSharper helped me understanding how and when to use them.
Maybe this could be an option for you, too.
精彩评论