Linq and lambda expression

2019-01-25 21:51发布

问题:

What is the difference between LINQ and Lambda Expressions? Are there any advantages to using lambda instead of linq queries?

回答1:

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.



回答2:

LINQ is Language integrated query, where is lamda expression are similar to Annonymous method for .Net 2.0.

You can't really compare them may be you are confused because LINQ is associated with lamda expression most of the time.

You need to see this article: Basics of LINQ & Lamda Expressions

EDIT: (I am not so sure, but may be you are looking for the difference between Query Syntax and Method Sytnax)

int[] numbers = { 5, 10, 8, 3, 6, 12};

//Query syntax:
IEnumerable<int> numQuery1 = 
    from num in numbers
    where num % 2 == 0
    orderby num
    select num;

 //Method syntax:
 IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);

In the above example taken from MSDN, Method Sytnax contains a lamda expression (num => num % 2 == 0) which works like a method, takes number as input and returns true if they are even.

They both are similar, and in the words of Jon Skeet, they both compile to similar code.



回答3:

In a nutshell:

LINQ is a quering technology (Language Integrated Query). LINQ makes extensive use of lambda's as arguments to standard query operator methods such as the Where clause.

A lambda expression is an anonymous function that contain expressions and statements. It is completely separate and distinct from LINQ.



标签: linq lambda