Skip to main content

How to use LINQ in Frends for data extraction and manipulation

A simple Linq query on Json data

Ossi Galkin avatar
Written by Ossi Galkin
Updated over a year ago

This tutorial will provide an example of using Linq in Frends. In this tutorial a simple Linq query will be used on Json formatted data. This tutorial recreates the Newtonsofts tutorial on this topic.

Linq is the most powerful and flexible way to transform data that is available in Frends and in C# in general. Linq can be used with objects, Json, Xml, and other datasets. Linq can be write in SQL-like query expressions or in more concise lambda expressions. This tutorial will use query expressions.

In this tutorial the following simple process will be created. The aim is to create a list of titles of blog posts.

First, Json data is saved in a variable named `#var.json` using an expression element (the smaller code element). The Json data could of course come from a real data source. The following expression is used to create data about blog posts.

@"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Announcing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}"

The expression is then assigned to the variable #var.json

The Task ConvertJsonStringToJToken is then used to parse, or deserialize, the data to JObject which is in a C# dynamic object created from JSON.

Then a code block (the bigger code element) is used to utilize Linq to create a list of titles. A Linq query expression is used to store a list of titles to the postTitles variable. The Linq expression only works with hardly typed variables, therefore we need to add a "cast to JObject" in front of the #result reference. The reason for this is that ConvertJsonStringToJToken can return any JToken e.g. JObject or JArray and thus technically it will return the dynamic type, which won't work directly in Linq.

The complete code for this step is:

{

var postTitles =
from p in ((JObject)#result[ConvertJsonStringToJToken].JToken)["channel"]["item"]
select (string)p["title"];

return postTitles;
}

It is important to remember to return the data from the code block and assign the returned data to a variable so it can be used later.

Finally, the Process will return a list of titles.

When the Process is run, a list of titles is returned from the Process.

Did this answer your question?