This tutorial will provide a example of how to use Linq in Frends. In this tutorial simple Linq query is used on Json formatted data. This tutorial recreates 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 following simple process will be created. Aim is create list of titles of blog posts.

First Json data is saved on a variable named `#var.json` using expression element (the smaller code element). Json data could of course come from some real data source. 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 variable #var.json

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

Then code block (the bigger code element) is used to utilize Linq to create a list of titles. Linq query expression is used to store a list of titles to postTitles variable. Linq expression work only with hardly typed variables, therefore we need to add a cast to JObject in front of #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.

Complete code for this step is

{

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

return postTitles;
}

It is important to remember to return data from the code block and assign 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 list of tittles is returned from the Process.

Did this answer your question?