Is It Linq or Lambda

Is it Linq or Lambda?

This is LINQ (using query syntax):

var _Results = from item in _List
where item.Value == 1
select item;

This is also LINQ (using method syntax):

var _Results = _List.Where(x => x.Value == 1);

It's interesting to note that both of these flavors will end up producing the exact same code. The compiler offers you a service by allowing you to express your wishes in the manner that you prefer.

And this is a lambda:

x => x.Value == 1

When you choose to use method syntax, LINQ is almost always seen around lambda expressions. But LINQ and lambdas are two totally different things, both of which can be used by themselves.

Update: As svick rightly points out, LINQ with query syntax is also implemented using lambda expressions (as mentioned earlier, the compiler allows you to write in query syntax but effectively transforms it to method syntax behind your back). This is just piling on the fact that both flavors are totally equivalent and will behave the same way (e.g. lambda expressions may cause closures to be created).

Difference between lambda and LINQ?

Language-Integrated Query (LINQ) is a set of features introduced in
Visual Studio 2008 that extends powerful query capabilities to the
language syntax of C# and Visual Basic

A lambda expression is an anonymous function that you can use to
create delegates or expression tree types. By using lambda
expressions, you can write local functions that can be passed as
arguments or returned as the value of function calls.

Linq uses Lambda expression in order to execute some of its functionalities.

Example:

new [] { "Dan", "Yossi", "Ben" }.Where(item => item.Length == 3);

Lambda expression: item => item.Length == 3

Linq: (from item in (new [] { "Dan", "Yossi", "Ben" }) where item.Length == 3)

linq lambda expression and '&' operator

I would like to add a correction here: actually both && and & are boolean AND operators in C# (when used with bool). However the former will do a short-circuit evaluation:

Consider A && B, if A is false then B will not be evaluated since the result will be false no matter what is the truthness of B.

And for the error you are getting, probably that's because your & operator is comparing a boolean expression and a lambda expression (function). Try this

MajorAdviserStudentAssignmentByAlpha majorAssignmentByAlpha = FindAllMajorAdviserStudentAssignmentByAlphas().FirstOrDefault(
a => a.MajorString == student.StudentMajor & String.Compare(student.StudentLastName, a.AlphaStart) >= 0 &
String.Compare(student.StudentLastName, a.AlphaEnd) <= 0);

if (majorAssignmentByAlpha != null)
return majorAssignmentByAlpha.Adviser;

Or equivalent in Linq Where() lambda expression

You can certainly do it within a Where clause (extension method). If you need to build a complex query dynamically, though, you can use a PredicateBuilder.

 var query = collection.Where( c => c.A == 1 || c.B == 2 );

Or using a PredicateBuilder

 var predicate = PredicateBuilder.False<Foo>();
predicate = predicate.Or( f => f.A == 1 );
if (allowB)
{
predicate = predicate.Or( f => f.B == 1 );
}

var query = collection.Where( predicate );

Linq and lambda expression

Linq is language integrated query. When using linq, a small anonymous function is often used as a parameter. That small anonymous function is a lambda expression.

var q = someList.Where(a => a > 7);

In the above query a => a > 7 is a lambda expression. It's the equivalent of writing a small utility method and passing that to Where:

bool smallMethod(int value)
{
return value > 7;
}

// Inside another function:
var q = someList.Where(smallMethod);

This means that your question is really not possible to answer. Linq and lambdas are not interchangeable, rather lambdas are one of the technologies used to implement linq.

Difference between LINQ Queries & Lambda expression

Query expressions only cover a small subset of the LINQ operators, and are only applicable when you have the actual expression involved to hand, rather than (say) having a Func<T, bool> to act as the predicate, in which case things become ugly. So instead of writing:

Func<Foo, bool> predicate = ...; // Get predicate from somewhere
var query = from x in collection
where predicate(x)
select x;

I'd much rather write:

Func<Foo, bool> predicate = ...; // Get predicate from somewhere
var query = collection.Where(predicate);

There are various other cases where using non-query expression syntax is simpler, particularly if your query only uses a single operator.

Query expressions are effectively translated into non-query expressions, so anything you can do in query expressions can be expressed in non-query expressions. Use query expressions where they make the code simpler and more readable; don't use them where they don't.

I have more information about how query expressions work in a blog post that you may be interested in.

What is the Efficiency and Performance of LINQ and Lambda Expression in .Net?

There's no one single answer that will suffice here.

LINQ has many uses, and many implementations, and thus many implications to the efficiency of your code.

As with every piece of technology at our fingertips, LINQ can and will be abused and misused alike, and the ability to distinguish between that, and proper usage, is only dependent on one thing: knowledge.

So the best advice I can give you is to go and read up on how LINQ is really implemented.

Things you should check into are:

  • LINQ and how it uses the methods and extension methods on existing collection types

    • How LINQ Works
    • How LINQ works internally (Stack Overflow)
    • How does coding with LINQ work? What happens behind the scenes?
  • How LINQ-to-objects and LINQ-to-SQL differs

    • What is the difference between LINQ query expressions and extension methods (Stack Overflow)
  • Alternatives to the new LINQ syntax, for instance, the usage of the .Where(...) extension method for collections

And as always, when looking at efficiency questions, the only safe approach is just to measure. Create a piece of code using LINQ that does a single, know, thing, and create an alternative, then measure both, and try to improve. Guessing and assuming will only lead to bad results.

Linq query or Lambda expression?

Query Expression compiles into Method Expression (Lambda expression), so there shouldn't be any difference, In your code though you are accessing First and FirstOrDefault which would behave differently.

See: Query Syntax and Method Syntax in LINQ (C#)

and LINQ Query Expressions (C# Programming Guide)

At compile time, query expressions are converted to Standard Query
Operator method calls according to the rules set forth in the C#
specification. Any query that can be expressed by using query syntax
can also be expressed by using method syntax. However, in most cases
query syntax is more readable and concise.

LINQ Lambda vs Query Syntax Performance

I have simulated your situation. And yes, there is difference between execution times of these queries. But, the reason of this difference isn't syntax of the query. It doesn't matter if you have used method or query syntax. Both yields the same result because query expres­sions are trans­lated into their lambda expres­sions before they’re com­piled.

But, if you have paid attention the two queries aren't same at all.Your second query will be translated to it's lambda syntax before it's compiled (You can remove ToList() from query, because it is redundant):

pTasks.Where(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending).Count();

And now we have two Linq queries in lambda syntax. The one I have stated above and this:

pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);

Now, the question is:

Why there is difference between execution times of these two queries?



Let's find the answer:

We can understand the reason of this difference by reviewing these:

- .Where(this IEnumerable<TSource> source, Func<TSource, bool> predicate).Count(this IEnumerable<TSource> source)

and

- Count(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Here is the implementation of Count(this IEnumerable<TSource> source, Func<TSource, bool> predicate):

public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
int count = 0;
foreach (TSource element in source) {
checked {
if (predicate(element)) count++;
}
}
return count;
}

And here is the Where(this IEnumerable<TSource> source, Func<TSource, bool> predicate):

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
if (source is Iterator<TSource>)
return ((Iterator<TSource>)source).Where(predicate);
if (source is TSource[])
return new WhereArrayIterator<TSource>((TSource[])source, predicate);
if (source is List<TSource>)
return new WhereListIterator<TSource>((List<TSource>)source, predicate);
return new WhereEnumerableIterator<TSource>(source, predicate);
}

Let's pay an attention to Where() implementation. It will return WhereListIterator() if your collection is List, but Count() will just iterate over source.
And in my opinion they have made some speed up in the implementation of WhereListIterator. And after this we are calling Count() method which takes no predicate as input and only will iterate on filtered collection.


And regarding to that speed up in the implementation of WhereListIterator:

I have found this question in SO: LINQ performance Count vs Where and Count. You can read @Matthew Watson answer there. He explains the performance difference between these two queries. And the result is:
The Where iterator avoids indirect virtual table call, but calls iterator methods directly.
As you see in that answer call instruction will be emitted instead of callvirt. And, callvirt is slower than call:

From bookCLR via C#:

When the callvirt IL instruction is used to call a virtual instance
method, the CLR discovers the actual type of the object being used to
make the call and then calls the method polymorphically. In order to
determine the type, the variable being used to make the call must not
be null. In other words, when compiling this call, the JIT compiler
generates code that verifes that the variable’s value is not null. If
it is null, the callvirt instruction causes the CLR to throw a
NullReferenceException. This additional check means that the callvirt
IL instruction executes slightly more slowly than the call
instruction.

What is proper way to write this linq lambda expression and deal with nulls?

Simply

double currentPopulation = detailmetrics
.Where(dm => dm.MetricScopeID == 2 && dm.MetricTypeID == 1 && dm.Timeframe.Equals("C"))
.Select(a => Convert.ToDouble(a.MetricValue))
.FirstOrDefault();


Related Topics



Leave a reply



Submit