LINQ - λ表达式

LINQ - λ表达式 首页 / LinQ入门教程 / LINQ - λ表达式

In LINQ, Lambda Expression is a function without a name. It makes the syntax short and clear. Though lambda expression is not readable as the LINQ query, it is equally important as the LINQ query, and it converts into lambda internally. The scope of the lambda expression is limited when we use it as an expression. Lambda Expression cannot be used afterward.

在LINQ中定义lambda表达式的语法为:

(Input Parameter) => Method Expression

lambda表达式是动态的,并在编译时决定类型。在上面左侧的lambda表达式中,我们有一个方括号(),它包含输入参数。

无涯教程网

参数的名称可以是任意名称,在此参数(=>;)前面是一个等于(=),后跟一个用于从左侧向右侧发送或传递参数的大于(>;)符号,在右侧,我们使用将从左侧参数传递的输入参数执行操作。

此整个语法形成Lambda表达式

这里,我们举一个常用表达式的例子:

X=>x+10

Here, x is an input parameter which is followed by => operator, and next to the operator, there is an expression that adds numeric 10 to the input variable (x). Now the output would increment the numeric 10 to x variable, which was the input parameter on the left-hand side of the Expression.

C#中Linq Lambda表达式示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
//list to store the countries type of string
            List countries = new List();

            countries.Add("India");

            countries.Add("US");

            countries.Add("Australia");

            countries.Add("Russia");
    //use lambda expression to show the list of the countries
            IEnumerable result = countries.Select(x => x);
    //foreach loop to display the countries
            foreach (var item in the result) 

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();
        }
    }
}

现在运行应用程序,它将显示国家/地区列表,如下所示,显示在控制台窗口的输出中。

输出

LINQ Lambda Expression Syntax

在上面的示例中,我们使用国家名称创建了列表对象,并使用lambda表达式从列表对象(国家)中选择国家。

这里,Select是我们用于从列表中选择的属性。X是输入参数,位于表达式的左侧,后跟=>;运算符。在表达式的右侧,我们有相同的输入参数表示,我们希望在不对其执行任何操作的情况下显示参数。我们没有具体说明它的任何条件。






祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

如何做好一场技术演讲 -〔极客时间〕

数据分析实战45讲 -〔陈旸〕

说透敏捷 -〔宋宁〕

手把手带你写一门编程语言 -〔宫文学〕

如何讲好一堂课 -〔薛雨〕

搞定音频技术 -〔冯建元 〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

运维监控系统实战笔记 -〔秦晓辉〕

好记忆不如烂笔头。留下您的足迹吧 :)