skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Method groups in LINQ

C# 2

Code card: Method groups in LINQ. Program output: <APPLE>, <PEAR>, <FIG> / True

When a lambda only forwards its argument, pass the method name. Same result, less noise. It is available since C# 2. The key line is var verbose = cart.Select(x => Display(x)).ToList() in methodgroup.cs. Run it and the output reads <APPLE>, <PEAR>, <FIG>, True.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
methodgroup.cs
string[] cart = ["apple", "pear", "fig"];
var verbose = cart.Select(x => Display(x)).ToList();
var concise = cart.Select(Display).ToList();
Console.WriteLine(string.Join(", ", concise));
Console.WriteLine(verbose.SequenceEqual(concise));
static string Display(string s) => $"<{s.ToUpper()}>";
Output
$ dotnet run methodgroup.cs
<APPLE>, <PEAR>, <FIG>
True