views:

770

answers:

8

Pour in your posts. I'll start with a couple, let us see how much we can collect.

To provide inline event handlers like

button.Click += (sender,args) =>
{
};

To find items in a collection

 var dogs= animals.Where(animal => animal.Type == "dog");

For iterating a collection, like

 animals.ForEach(animal=>Console.WriteLine(animal.Name));

Let them come!!

+3  A: 

Returning an custom object:

var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname});
Andreas Grech
Did you know, you can just do new {x.name, x.surname} ? The properties will be lowercase as in this example.
leppie
A: 

Casting a collection of objects.

foreach(MyCustomObject co in objects.Select(o => o As MyCustomObject))
{
    ...
}
a_hardin
Check out Enumerable.Cast and Enumerable.OfType: http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx
David B
This is not needed. Is it?
leppie
If any items in objects are not of type MyCustomObject, then the resulting sequence will contain nulls. Probably not what you'd want.
Daniel Earwicker
A: 

Creating an accumulator.

    static Func<int, int> Foo(int n)
    {
        return a => n += a;
    }

Note the closure usage here. it's creating an accumulator that "remembers" the value of n between calls - without a class or instance variable.

TheSoftwareJedi
A: 

To express an unnamed function.

Daniel Earwicker
+2  A: 

One line function

Func<int, int> multiply = x => x * 2;
int y = multiply(4);
Binoj Antony
+1  A: 

Here's a slightly different one - you can use them (like this) to simulate the missing "infoof"/"nameof" operators in C# - i.e. so that instead of hard-coding to a property name as a string, you can use a lambda. This means that it is validated at compile time (which strings can't be).

There is obviously a performance cost to this, hence "just for fun", but interesting...

Marc Gravell
A: 

For aggregate operations with Linq:

public Double GetLengthOfElements(string[] wordArr) {

   double count = wordArr.Sum(word => word.Length);
   return count;
}

Sure beats using foreach

lomaxx
+1  A: 

With method invoker to update UI from a multi threaded componenet event

void Task_Progress(object sender,TaskProgressArgs  e)
{
    BeginInvoke(new MethodInvoker(() => UpdateProgress(e)));
}
Priyan R