Function Name Instead of Lambda in Linq Functions
I did not realize that functions can fill in for predicates directly without lambda notation. To illustrate, consider the following:
void Main()
{
var words = new List<string>()
{
"therapists",
"s words",
"slang",
"mustache",
"sean connery"
};
var s_words = words.Where(w => w.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase));
foreach(var word in s_words)
{
Console.WriteLine(word);
}
}
It works, but it’s a rather long lambda, which is why I broke it out of the for loop. Let’s put that logic into a function, getting this:
void Main()
{
var words = new List<string>()
{
"therapists",
"s words",
"slang",
"mustache",
"sean connery"
};
foreach(var word in words.Where(w => SWords(w)))
{
Console.WriteLine(word);
}
}
public bool SWords(string word)
{
return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}
That’s better. And you might find yourself using your test in other places in the code, so it’s useful to have the function. What I found out recently, is that you can go one step further:
void Main()
{
var words = new List<string>()
{
"therapists",
"s words",
"slang",
"mustache",
"sean connery"
};
foreach(var word in words.Where(SWords))
{
Console.WriteLine(word);
}
}
public bool SWords(string word)
{
return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}
In this example, the savings may not look drastic. But for several chained methods you can gain a lot of brevity and clarity.


