I have written some LINQ where I check against a database whether or not the username is unique when I am adding a new user. My code (see below) works, but is there a better way to do this? I am currently relying on trapping an error if the username does not exist.
try
{
var User = (from u in _database.Users
where u.UserID == strUserName
select u).First();
if (User != null)
{
blnUnique = false;
}
}
catch
{
blnUnique = false;
}
You can use the Enumerable.Any<TSource>() extension method:
Here’s an alternative way of expressing this using a lambda:
Note that the equals operator on the String class will make a case-sensitive ordinal comparison. If you wish to make a case-insensitive comparison you’ll have to use the String.Equals method: