Query Code with C# LINQ
The backbone of the NDepend tool is its ability to query its code model with a C# LINQ query, This feature is named CQLinq. The idea is to query code with C# LINQ the same way as relational data is queried with SQL.
All NDepend features are based on CQLinq as explained here. This means that most of code queries you will deal with are provided out-of-the-box like default code rules, or will be generated by a NDepend feature.
Nevertheless you can write your own code query like for example this query that matches complex methods:
from m in JustMyCode.Methods
where m.CyclomaticComplexity > 20
select new { m, m.CyclomaticComplexity, m.NbLinesOfCode }
Notice in the screenshot below the View Description button unchecked, which means that the query editable source code is shown instead instead of the query description (embedded in query source comments).
The best ways to get started with querying code with NDepend are:
Playing with the NDepend Search panel to generate all sorts of code queries like queries to match some elements by name, by complexity, by size, by usage...
For example the search panel can generate a code query similar to the one just presented above by searching for methods by complexity. Most of the time the query generated will be enough but with the button Edit Query you can edit the query generated to refine it to your needs.
Query Generated:
from m in Application.Methods
where m.CyclomaticComplexity >= 20 && !m.IsAbstract
orderby m.CyclomaticComplexity descending
select new { m, m.CyclomaticComplexity }- Review the source code of the default code rules.
- Generate a query from right clicking a code element in the Visual Studio code editor panel or in the Visual Studio solution explorer panel. The select menus are rich. From a given code element, you will be able to generate most of code queries you will need.
- The NDepend code query editor proposes code completion. Also the editor allows to browse the NDepend.API Code Model documentation (see root link and the stop/next/previous buttons in the screenhsot):
- Refer to the documentation:
-
Watch this 3 minutes video to get started with querying your code with NDepend: