Query Methods in Roslyn Syntax API

In previous post I discussed about Roslyn Syntax API: First Look .

In pervious approach I traversed manually in Syntax Tree to the Method level and started from Compilation Unit level to get the Method Arguments. Rather than manually navigating the Syntax Tree, you can use LINQ to get the parameter in the function. We can directly apply LINQ on Syntax Tree.


If you remember from last post out Syntax Tree was as below,


Now if we want to print method name using LINQ in Syntax tree then,


Underneath LINQ is also doing the manual traversing of the Syntax tree. When you execute above code you will get output as below,


If you have more than one parameters in the method then you can print them like below,


And then you can traverse using foreach to print all the method names. For your reference all the code discussed in this post is given below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace ConsoleApplication30
class Program
static void Main(string[] args)

SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
@"class Animal
void Display(string animalName,int abc)
Console.WriteLine(""Animal name is "" + animalName);
var root = (CompilationUnitSyntax) tree.Root;

var paraMeterList = from r in root.DescendentNodes().OfType<MethodDeclarationSyntax>()
where r.Identifier.ValueText == "Display"
select r.ParameterList.Parameters.First();

var AllParaMeterList = from r in root.DescendentNodes().OfType<MethodDeclarationSyntax>()
where r.Identifier.ValueText == "Display"
select r.ParameterList.Parameters;
foreach (var r in AllParaMeterList)

foreach (var a in r)





When you execute above listed code, you will get output as below,


In this way you can traverse Syntax tree using LINQ. I hope this post is useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

4 thoughts on “Query Methods in Roslyn Syntax API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s