Succinct C# Methods

If you are like me, you are always trying to write your code as efficiently as possible. So, I thought I would start a series of posts that reflect my research on this topic. The first article in this series relates to LINQ and Boolean methods.

Let's say we have a method that checks the database if a user is a member of a specific role. The method might look something like this.

public bool UserIsInRole(int userId, int roleId)
{
	//	returns IQueryable
	var result = (from r in db.UserRoles()
		where r.UserId == userId && r.RoleId == roleId
		select r);
}

The LINQ will return an IQueryable. We could use the FirstOrDefault() method which will return the first matching result. Then we could check if the result is null and return true or false. That sounds like a lot of work, right?

Another alternative could be use the Any() method of the IQueryable result. This would return a true or false based on the result. Until recently, my method would look like this.

public bool UserIsInRole(int userId, int roleId)
{
	var result = (from r in GetUserRoles()
		where r.UserId == userId && r.RoleId == roleId
		select r);

	if (result.Any())
	{
		return true;
	}
	else
	{
		return false;
	}
}

This works and will give us the correct Boolean result. However, it's wordy and there is a better option. Consider the fact that the Any() method returns a Boolean result. Why not just return that? Our method now looks much neater.

public bool UserIsInRole(int userId, int roleId)
{
	var result = (from r in GetUserRoles()
		where r.UserId == userId && r.RoleId == roleId
		select r);

	return result.Any();
}

You can even join two results together. Say, for example, you have two conditions that must be met before a true result can be returned from your method. Simply concatenate the two conditions together like this.

public bool UserIsInRole(int userId, int roleId, string colour)
{
	var result = (from r in GetUserRoles()
		where r.UserId == userId && r.RoleId == roleId
		select r);

	return result.Any() && colour == blue;
}

That is much easier to write and read.

Til next time ...