Does anyone stick to any rules (or are you forced to stick to any rules by your employer?) when choosing to use either LINQ query syntax or a Lambda expression inside one of the LINQ extension methods? This applies to any Entities, SQL, objects, anything.
At our workplace, my boss doesn't like lambda at all and he'd use the query syntax for anything, which in some cases, I find are less readable.
var names = collection.Select(item => item.Name);
var names = from item in collection
select item.Name;
Maybe when adding a condition, the Lambda I find gets a little messy, where the
var names = collection.Where(item => item.Name == "Fred")
.Select(item => item.Name);
var names = from item in collection
where item.Name == "Fred"
select item.Name;
Just out of interest: how does the compiler treat this one? Does anyone know how the above LINQ query will compile into lambda? Will the Name
property be called for each element? Could we do this instead and potentially improve the performance? Would this mean lambda is slightly more controllable in terms of performance?
var names = collection.Select(item => item.Name)
.Where(name => name == "Fred");
Certainly when we start using more and more expressions, the lambda gets messy and I'd start to use the query syntax here.
var names = collection.Where(item => item.Name == "Fred")
.OrderBy(item => item.Age)
.Select(item => item.Name);
var names = from item in collection
where item.Name == "Fred"
order by item.Age
select item.Name;
There are also a few things that I find can't be done with the query syntax. Some of them you'd think would be really simple (particularly aggregate functions), but no, you have to add one of the LINQ extension methods to the end, which imo, look neater with a lambda expression.
var names = collection.Count(item => item.Name == "Fred");
var names = (from item in collection
where item.Name == "Fred"
select item).Count()
Even for some of the simple lambda chains, ReSharper is suggesting I convert them to LINQ querys.
Can anyone else add to this? Does anyone have their own little rules or does their company suggest/force the use of one?