Lambdas are just something that, once you get your head around, you "get" it. If you're using a delegate currently, you can replace it with a lambda. Also the System.Action<...>
, System.Func<...>
, and System.Predicate<...>
additions are nice shortcuts. Some examples showing syntax would be helpful though (warning: they are inane but I wanted to illustrate how you can swap functions):
public static void Main()
{
// ToString is shown below for clarification
Func<int,string,string> intAndString = (x, y) => x.ToString() + y.ToString();
Func<bool, float, string> boolAndFloat = (x, y) => x.ToString() + y.ToString();
// with declared
Combine(13, "dog", intAndString);
Combine(true, 37.893f, boolAndFloat);
// inline
Combine("a string", " with another", (s1, s2) => s1 + s2);
// and multiline - note inclusion of return
Combine(new[] { 1, 2, 3 }, new[] { 6, 7, 8 },
(arr1, arr2) =>
{
var ret = "";
foreach (var i in arr1)
{
ret += i.ToString();
}
foreach (var n in arr2)
{
ret += n.ToString();
}
return ret;
}
);
// addition
PerformOperation(2, 2, (x, y) => 2 + 2);
// sum, multi-line
PerformOperation(new[] { 1, 2, 3 }, new[] { 12, 13, 14 },
(arr1, arr2) =>
{
var ret = 0;
foreach (var i in arr1)
ret += i;
foreach (var i in arr2)
ret += i;
return ret;
}
);
Console.ReadLine();
}
public static void Combine<TOne, TTwo>(TOne one, TTwo two, Func<TOne, TTwo, string> vd)
{
Console.WriteLine("Appended: " + vd(one, two));
}
public static void PerformOperation<T,TResult>(T one, T two, Func<T, T, TResult> func)
{
Console.WriteLine("{0} operation {1} is {2}.", one, two, func(one,two));
}
Mostly what confused me was the shortcut syntax, for example when using System.Action to just execute a delegate with no parameters you could use:
var a = new Action(() => Console.WriteLine("Yay!"));
Or you could do:
Action a = () => Console.WriteLine("Yay");
When you've got an Action
, Func
, or Predicate
that takes one argument you can omit the parenthesis:
var f = new Func<int, bool>(anInt => anInt > 0);
or:
// note: no var here, explicit declaration
Func<int,bool> f = anInt => anInt > 0;
instead of:
Func<int,bool> f = (anInt) => anInt > 0;
or to go to the extreme:
Func<int,bool> f = (anInt) =>
{
return anInt > 0;
}
As shown above, single line lambdas do not require the return statement, though multiline Func
lambdas do.
I think you will find the best way to learn how to use lambdas is to work a lot with collections and include System.Linq in your using namespaces - you will see a ton of extension methods for your collections and most of these methods allow you to exercise your knowledge of lambdas.