I love the Coalesce operator in C#

11. August 2009

Recently I was given a requirement where clients can enter alternate text for particular content and even alternate text to the alternate text. They wanted it so that the default text would only show if the first and second alternate text was null.

So basically we have :

Text, varchar(max)
AlternateText1, varchar(max)
AlternateText2, varchar(max)

Try to show "AlternateText2"
If  "AlternateText2" is null – show "AlternateText1"
If "AlternateText1" is null – show "Text"

So what is easier?

     
string ItemText = string.Empty;
if (string.IsNullOrEmpty(c.AlternateText2))
{
	if (string.IsNullOrEmpty(c.AlternateText1))
	{
		ItemText = c.Text;
	}
	else
	{
		ItemText = c.AlternateText1;
	}
}
else
{
	ItemText = c.AlternateText2;
}

Or.... integrating it into our LINQ Query itself?

                                       
from u in something.DefaultIfEmpty()
select new
{
	ID = c.ID,
	ItemText = c.AlternateText2 ?? c.AlternateText1 ?? c.Text ?? "Oops, no text available",
	ItemDate = c.ItemDate,
	FirstName = u.FirstName,
	LastName = u.LastName,
})

That is all, nothing special here – Maybe it is the cold medicine this morning, but I was just really thankful that I did not have to write a lot of code to fulfill a fairly simple requirement.

.NET 3.5, LINQ, General , ,

Add comment


(Will show your Gravatar icon)

Click to Refresh Captcha
biuquote
  • Comment
  • Preview
Loading