Archive for category .Net
Fun with C# and in-memory linq queries
Posted by Joshua Smyth (Admin) in .Net, C#, Programming on March 6, 2009
Linq is probably one of my favoriate features of C# and to show you why here is a quick code demonstration.
Quite often you want to write some code that has to iterate over the collection; For example: Finding an element in a list of to see if it is present.
For a program I’m working on at my day job, I decided to implement a rule that says each account must have at least one user who has admin rights for the account, and here is some code that checks that condition.
(Note to self: Find good code formatting plug-in for wordpress)
bool AtLeastOneAdmin = false;
foreach(User u in Users)
{
if (u.isAdmin)
{
AtLeastOneAdmin = true;
break;
}
}
Pretty straightforward, Now lets write the same code using Linq:
Bool AtLeastOneAdmin = (from u in users where u.isAdmin == true select u).Count() > 0;
That does the exact same thing and only takes up one line of code!