As an intellectual exercise I decided to write up 3 different ways to perform the same LINQ tasks. Actually I saw a comment on one of Don Box’s blog posts where someone asked why the Find and Exists methods weren’t static and I suddenly realized that they were, just with different names!
Since LINQ is simply an internal DSL that wraps calls to extension methods I realized these methods must exist for us to call them explicitly as well. Here is how you can perform a Find or an Exists using LINQ (or not).
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
// Find an assembly that starts with System.
Func<Assembly, bool> startsWithSystem = a => a.FullName.StartsWith(“System”);
//List<T>.Exists equivalents for any enumerable
bool extensionAny = assemblies.Any(startsWithSystem);
bool explictAny = Enumerable.Any(assemblies, startsWithSystem);
bool linqAny = (from a in assemblies where startsWithSystem(a) select a).Any();
Debug.Assert(extensionAny == explictAny == linqAny == true);
// List<T>.Find equivalents for any enumerable
int extensionWhere = assemblies.Where(startsWithSystem).Count();
int explicitWhere = Enumerable.Where(assemblies, startsWithSystem).Count();
int linqWhere = (from a in assemblies where startsWithSystem(a) select a).Count();
Debug.Assert(extensionWhere == explicitWhere && extensionWhere == linqWhere);
|
You must log in to post a comment.