How to use LINQ in a Workflow

Question

Can I use a LINQ Query such as the following in a Workflow?

 private static void ShowQueryWithCode(IEnumerable<string> names)
{
    Console.WriteLine("Linq Query in Code - show names that start with 'R'");

    // Assuming there are no null entries in the names collection
    var query = from name in names where name.StartsWith("R") select name;

    // This is the same thing as 
    // var query = names.Where(name => name.StartsWith("R"));
    foreach (var name in query)
    {
        Console.WriteLine(name);
    }

    Console.WriteLine();
}



Answer


Yes, you can use LINQ with a Workflow in exactly the same way.

Download Sample Code

 

Step 1: Create a Workflow with an In Argument of type IEnumerable<string>

Here you can see that I've added the in argument

argument

Step 2: Add a Variable for the query of type IEnumerable<string>

Before you can add a variable you need to include an activity which has variables.  In this workflow I've added a sequence.

variable

Step 3: Assign the query the LINQ expression you want to use

You can use a method chain or query syntax.

expression

Step 4: Iterate over the collection

In the completed workflow I used a ForEach<string> activity to iterate the list of names and write them to the console.

Workflow1

Summary

This example uses C# in .NET 4.5 but the same technique can be used with Visual Basic.

When you run it you can see that both methods work the same.

console

Happy Coding!

Ron Jacobs

https://blogs.msdn.com/rjacobs

Twitter: @ronljacobs