Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Any suggestions how I could simplify this LINQ query?

from type in assembly.GetTypes()
where type.IsPublic && !type.IsSealed && type.IsClass
where (from method in type.GetMethods()
       from typeEvent in type.GetEvents()
       where method.Name.EndsWith("Async")
       where typeEvent.Name.EndsWith("Completed")
       let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
       where typeEvent.Name == operationName + "Completed"
       select new { method, typeEvent }).Count() > 0
select type;

assembly is of type System.Reflection.Assembly. If you need more information, just ask.

share|improve this question
1  
What I can see immediately is that you could replace Count() > 0 with Any(), which is simpler and also more efficient. –  svick Jul 11 '12 at 18:38

1 Answer 1

up vote 2 down vote accepted

You can do a join between the methods and events :

from type in assembly.GetTypes()
where type.IsPublic && !type.IsSealed && type.IsClass
where (from method in type.GetMethods()
        join typeEvent in type.GetEvents()
            on method.Name.Replace("Async", "Completed") equals typeEvent.Name
        select new { method, typeEvent }).Any()
select type;
share|improve this answer
    
The way you're using Replace() means this code will most likely work, but it's not guaranteed to work for methods with “weird” names (like PerformAsyncOperationAsync). –  svick Jul 11 '12 at 19:33
    
Well other than the rare case that @svick mentioned, this could work. I'll probably just make a utility method to make sure only "Async" at the end is replaced. –  JKor Jul 11 '12 at 22:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.