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.


Posted

in

by

Comments

One response to “Function Name Instead of Lambda in Linq Functions”

  1. Paula Avatar
    Paula

    Hey Tim!
    I can’t comment on this post at all (due to lack of technical chops), but I wanted to say that Ted and I read through a bunch of your archived posts on different topics and really enjoyed them.

    You’ve got an intriguing range of interests. I don’t watch BG, but I LOVE All Along the Watchtower so it’s neat that the song was a plot point of sorts. And I can relate to your posts about hiring/interviewing and difficulties inherent in those processes.

    Also enjoyed your discussion about Bill Gates and Steve Jobs. (And many others -)

    Hint: If you’re ever looking for topics, write about CSS!

    Paula