I find that I'm using LINQ just about any time that I would have previously written a loop to fill a container. I use LINQ to SQL as my ORM and lots of LINQ everywhere else.
Here's a little snippet that I wrote for an Active Directory helper class that finds out if a particular user is an a particular group. Note the use of the Any() method to iterate over the user's authorization groups until it finds one with a matching SID. Much cleaner code than the alternative.
private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
if (group == null || group.Sid == null)
{
return false;
}
return user.GetAuthorizationGroups()
.Any( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 );
}
Alternative:
private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
if (group == null || group.Sid == null)
{
return false;
}
bool inGroup = false;
foreach (var g in user.GetAuthorizationGroups())
{
if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
{
inGroup = true;
break;
}
}
return inGroup;
}
or
private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
if (group == null || group.Sid == null)
{
return false;
}
foreach (var g in user.GetAuthorizationGroups())
{
if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
{
return true;
}
}
return false;
}
Here's a snippet that does a search against a repository, orders, and converts the first 10 matching business objects into a view-specific model (Distance
is the Levenshtein edit distance of the matching model's unique id from the uniqueID parameter).
model.Results = this.Repository.FindGuestByUniqueID( uniqueID, withExpired )
.OrderBy( g => g.Distance )
.Take( 10 )
.ToList()
.Select( g => new GuestGridModel( g ) );