-
February 12th, 2013, 08:54 AM
#1
Been out of real C# for awhile - help me decipher this code
Just got the ".NET Framework 4.5 Expert Programming Cookbook" - going through the first example of implementing the Repository pattern. I've been around code for a long time (14+ years) but there's some new syntax that I'm not familiar with:
Code:
public bool IsUsernameUnique(string userName)
{
bool exists = _users.Exists(u => u.UserName == userName);
return !exists;
}
I'm not getting this part:
u => u.UserName == userName
_users is a List<User> collection.
Is this Linq ?? What's the u => ?
-
February 12th, 2013, 10:40 AM
#2
Re: Been out of real C# for awhile - help me decipher this code
haha, if I'd kept reading the book explains it:
Coming back to the IsUsernameUnique method, it makes use of the predicate feature
provided by .NET. Predicate allows us to loop over a collection and find a particular item.
Predicate can be a static function, a delegate, or a lambda. In our case it is a lambda.
bool exists = _users.Exists(u=>u.UserName==userName);
In the previous statement, .NET loops over _users and passes the current item to u. We
then make use of the item held by u to check whether its username is equal to the username
entered by the user
Sweet book! Given that there's 43 views on this thread and no responses, I'd say this is not a particularly common way of doing this - but definitely looks like "Expert" code to me
-
February 12th, 2013, 02:40 PM
#3
Re: Been out of real C# for awhile - help me decipher this code
Originally Posted by progrmr
Given that there's 43 views on this thread and no responses, I'd say this is not a particularly common way of doing this - but definitely looks like "Expert" code to me
LINQ is a common way of doing things. As far as the 43 views..., keep in mind that folks here are volunteers and with the various time zones around the world, not everyone may be awake when you first posted, so a response may take up to a day or two.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|