Fluent and Query Expression - Is There Any Benefit(S) of One Over Other

Fluent and Query Expression — Is there any benefit(s) of one over other?

Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage multiple range variables. This happens in three situations:

  • When using the let keyword
  • When you have multiple generators (from clauses)
  • When doing joins

Here's an example (from the LINQPad samples):

string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };

var query =
from fullName in fullNames
from name in fullName.Split()
orderby fullName, name
select name + " came from " + fullName;

Now compare this to the same thing in method syntax:

var query = fullNames
.SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
.OrderBy (x => x.fName)
.ThenBy (x => x.name)
.Select (x => x.name + " came from " + x.fName);

Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:

var query =
from c in db.Customers
let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here
where totalSpend > 1000
from p in c.Purchases
select new { p.Description, totalSpend, c.Address.State };

LINQ query expression versus fluent (dot) notation

Either one works the same but I would choose the one that is most readable.

C# compiler sees Fluent syntax or Query Expression?

A "compiler" is by definition a device which translates a text written in one language into another language.

The C# compiler logically translates C# programs that contain query expressions into C#-without-query-expressions, and then translates those programs into IL. (Note that it need not actually do that middle stage of translation; it must behave as though it does so, but if the compiler writers are clever enough to skip that intermediate step and still get the right output then we certainly can do so.)

Reflector is also a compiler. It translates IL into C#. How it does so is it's business.

You can't make any conclusions about what the C# compiler does based on the output of Reflector; they are completely different programs written by different people to solve different problems.

C# compiler sees Fluent syntax or Query Expression?

A "compiler" is by definition a device which translates a text written in one language into another language.

The C# compiler logically translates C# programs that contain query expressions into C#-without-query-expressions, and then translates those programs into IL. (Note that it need not actually do that middle stage of translation; it must behave as though it does so, but if the compiler writers are clever enough to skip that intermediate step and still get the right output then we certainly can do so.)

Reflector is also a compiler. It translates IL into C#. How it does so is it's business.

You can't make any conclusions about what the C# compiler does based on the output of Reflector; they are completely different programs written by different people to solve different problems.

LINQ Lambda Expression (Fluent Programming) to retrieve an average of multiple occurrences

Use the Average LINQ method:

var average = _mTelMgr.AllCellInfo
.OfType<CellInfoLte>()
.Average(c => c.CellSignalStrength.Dbm);

This code finds all CellInfoLte instances in collections (OfType<CellInfoLte>), gets CellSignalStrength.Dbm values, and calculates the average (Average).

Duplicate results with GroupBy using Linq Query Expression but not using Fluent Syntax

When you used method syntax you were not grouping on two different values, rather you were grouping on only the country and transforming all of the elements into Carriages. If you wanted to use query syntax to do that the syntax would be:

var query = (from t in trains
group t.Carriages by t.Country.ToUpper()
into g
select new
{
Country = g.Key,
TotalCarriages = g.Count(),
SumCarriage = g.SelectMany(c => c).Sum(l => l.Length)
}).ToList();

LINQ operators versus LINQ methods: limitations, pros / cons of one over the other?

The term "operator" in LINQ isn't the same as "operator" in the normal sense of C# language operators, (+, && etc). The LINQ standard query operators are just the LINQ methods which are expected to be available where possible through most providers (and the ones made available through LINQ to Objects in particular).

Were you actually asking about the pros and cons of using query expressions like this:

var query = from item in source
where item.SomeProperty == 5
select item.OtherProperty;

vs the "fluent interface" or "dot notation" of normal extension method calls:

var query = source.Where(item => item.SomeProperty == 5)
.Select(item => item.OtherProperty);

? If so, I can write about that in more detail, but basically:

  • There'll generally be no performance difference, as query expressions are effectively translated by the compiler into the latter syntax. Occasionally there are overloads you can use from dot notation which aren't available via query expressions, and you may be able to make things more efficient that way.
  • Operators which use multiple delegates (e.g. Join, GroupBy) tend to be more readable in query expression syntax
  • If your query would use lots of transparent identifiers in query expression syntax, the dot notation is likely to be ugly
  • If your query is very simple (just a Where and/or Select) then dot notation is likely to be simpler
  • If you're using methods which are unsupported by query expressions (e.g. Count(), ToList() etc) then having to bracket the query expression can be ugly


Related Topics



Leave a reply



Submit