Aman
Aman

Reputation: 71

Compile Linq Expression using Roslyn

Is there a way to compile the following string in C# string linqExpression = "(seq) => seq.Average()" using roslyn?

Instead of doing this:

SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@" using System; 
    using System.Linq; 
    public class RoslynLinq 
    { 
        public void Execute(int[] a) 
        { 
            Func<int[], double> func = (seq) => seq.Average(); 
            Console.WriteLine(func(a)); 
        } 
    }"); 

Can I do:

SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText("Func<int[], double> func = (seq) => seq.Select((x)=>x).Average()");

Upvotes: 2

Views: 1186

Answers (1)

SLaks
SLaks

Reputation: 888047

It sounds like you're actually asking whether you can parse a statement without a containing function or class.

Just pass SourceCodeKind.Script and that will work fine.

Upvotes: 1

Related Questions