How to write Fluent Linq Queries?
This article helps you to understand Linq a little more easily. I have used Fluent expressions to write the LINQ queries.I have also used normal queries to that you can differentiate between the fluent queries and the normal queries.Its easy to write both types of queries, you have to decide in which way you want to write that.
Example 1:
We have an array of strings named 'names'.string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
Now we are using the IEnumerable to specify the Datatype of the query that is string.We can use var also.Here we have used the Where clause,OrderBy clause and the select clause,the order is not important between Where and OrderBy clauses, but select must be the last Clause.Since where clause filters the data so it is always recommended that to use where clause before any clauses so that your query will be a little faster if you have many values in your query.Like when you are doing a cross join you want your query to run faster, at that time you can use this type of expressions.
IEnumerable
.Where (n => n.Contains ("a"))
.OrderBy (n => n.Length)
.Select (n => n.ToUpper());
foreach(var i in query)
{
Console.WriteLine(i);
}
Here at first i am filtering my list and then ordering it by its length i.e. smaller length word will be at first and then the bigger word length.Afetr that the names are projected out as an upper case.
ORvar query = names
.Where (n => n.Contains ("a"))
.OrderBy (n => n.Length)
.Select (n => n.ToUpper());
foreach(var i in query)
{
Console.WriteLine(i);
}
Same as that of previous one but using the keyword var.
// The same query constructed progressively:
This is same as that of previous one but we are doing all the things progressively.At first we are filtering it then ordering it and then selecting out using the select clause.IEnumerable
foreach(var i in filtered)
{
Console.WriteLine(i);
}
IEnumerable
foreach(var i in sorted)
{
Console.WriteLine(i);
}
IEnumerable
foreach(var i in finalQuery)
{
Console.WriteLine(i);
}
Example 2:
In this example we are selecting out only those names whose length is the smallest.it can be done in four ways given below.string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
names.Where (n => n.Length == names.OrderBy (n2 => n2.Length)
.Select (n2 => n2.Length).First())
foreach(var i in names)
{
Console.WriteLine(i);
}
var query =
from n in names
where n.Length == (from n2 in names orderby n2.Length select n2.Length).First()
select n;
query.Dump ("Same thing as a query expression");
query =
from n in names
where n.Length == names.OrderBy (n2 => n2.Length).First().Length
select n;
query.Dump ("Reformulated");
query =
from n in names
where n.Length == names.Min (n2 => n2.Length)
select n;
query.Dump ("Same result, using Min aggregation");
If you have any doubts feel free to ask.