Reputation: 936
I'm trying to implement a Diagnostic Analyzer for Collection initializer and its corresponding Code Fix provider.
Wrong Code:
var sampleList= new List<string>();
sampleList.Add("");
sampleList.Add("");
After CodeFix:
var sampleList= new List<string>(){"", ""};
But I'm stuck at this problem that once I get a node for LocalDeclarationStatement, I'm not aware if there exists a way to get the very next adjacent node from the parent.
In the above Picture I require both the ExpressionStatement after analyzing the LocalDeclarationStatement
REQUIREMENT for analyzer
LocalDeclarationStatement
, a collection that is already initialized but doesnt contain CollectionInitializerExpression
Add
method on the same collectionREQUIREMENT for Code fix
Add
method on the collectionUpvotes: 1
Views: 178
Reputation: 19031
You can do something like:
var declarationStatement = ...;
var block = (BlockSyntax)declarationStatement.Parent;
var index = block.Statements.IndexOf(declarationStatement);
var nextStatement = block.Statements[index + 1];
Upvotes: 3
Reputation: 26318
Wouldn't you just need to turn the concrete block into list, and check?
var nodes = yourSyntaxTree.DescentNodes().ToList();
for(var i = 0; i < nodes.Count; i++){
var localDeclarationStatement = nodes[i] as LocalDeclarationStatement;
if(localDeclarationStatement==null && i + 1 >= nodes.Length)
continue;
var expressionStatement = nodes[i+1] as ExpressionStatement;
if(expressionStatement==null)
continue;
// there you have it.
}
Upvotes: 1