.NET/C# Lambda Expressions
By Dag, on December 30th, 2016using System.Linq;
The >= lambda operator in .NET can be a really handy match expression tool. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. Here I add a few times I've used it for reference.
Finding the last item in a list:
List<string s> l = new List<string s>();
string TheLastItem = l.FindLast((string ListItem) => ListItem.Length > 5);
Equivalent to:
List<string s> l = new List<string s>();
String TheLastItem;
foreach (string ListItem in l) {
if (ListItem.Length > 5)
TheLastItem = ListItem; // Will end up with the last.
}
Array ordering:
PopLines = PopLines.OrderByDescending(line => Int32.Parse(line.Split('\t')[1])).ToArray();
EventHandler:
p.Exited += (object senderr, EventArgs ee) => { Program_IsRunning["mailpv"] = false; };
Sorting files by creation date:
DirectoryInfo MBAMLogDirInfo = new DirectoryInfo(MBAMLogDir);
FileInfo[] MBAMLogs = MBAMLogDirInfo.GetFiles("mbam-log-*").OrderByDescending(f => f.CreationTime).ToArray();
Check if a service exists:
ServiceController ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "VPNBypassService");
if (ctl != null)
return true;
else
return false;
Coming from other languages, the lambda expression/operator tend to give a powerful first impression.