Lambda表达式在实际编程中的使用

发布于 2024-07-26 05:28:10 字数 660 浏览 5 评论 0原文

我是一名经验丰富的 C# 开发人员,过去 7 年一直致力于 LOB 应用程序,我在理解 Lambda 表达式在编程中的用法方面遇到了一些问题。

据我了解,它在

  1. 使用 LINQ(分组、选择、Where 等)的情况下很有用。
  2. 我们可以将 Lambda 表达式作为参数传递给任何函数,因此它可以用来代替委托或匿名函数或普通函数功能。
  3. 我们可以创建通用的 lambda 函数,它接受任何数据类型变量作为参数,并可以返回任何数据类型,例如

    MyFirstLambdaFunc((val1,val2) => val1+val2) 
      公共 R MyFirstLambdaFunc(Func lambda 表达式,T x,T y) 
      { 
        R 结果 = lambda 表达式(x, y); 
        返回结果; 
      } 
      
  4. 编码可以是紧凑的

现在的问题是:

  1. 是否存在还有其他优点吗?
  2. 当我们将 lambda 表达式作为函数传递时,我们可以只传递单行操作吗?
  3. 有人可以提供一些案例研究或一些实际示例文件吗?

提前致谢

Harish Bhattbhatt

I am an experienced developer in C# and working on LOB application from last 7 Years, I have some issues in understanding the usage of Lambda expression in programming.

As far as I understand, it is useful in case of

  1. Working with LINQ (Grouping, Select,Where etc..)
  2. We can pass Lambda expression to any function as argument, so it can be used in place of delegate or anonymous function or normal function.
  3. We can create generic lambda function which takes any datatype variable as argument and can return any datatype, e.g.

    MyFirstLambdaFunc((val1,val2) => val1+val2)
    public R MyFirstLambdaFunc(Func lambdaexpression,T x,T y)
    {
      R Result = lambdaexpression(x, y);
      return Result;
    }
    
  4. Coding can be compact

Now the question is:

  1. Are there any other advantages?
  2. When we pass lambda expression as function, can we pass only a single line operation?
  3. Can anybody have some case study or some practical example document?

Thanks in Advance

Harish Bhattbhatt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夜访吸血鬼 2024-08-02 05:28:10

对于非表达式树,您当然可以编写多行 lambda 表达式。 就在今天早上,我写了一些大致内容:

 var query = foo.Select(x => {
               string text = x.Value;
               int delimitedIndex = text.IndexOf(' ');
               return int.Parse(text.Substring(0, delimitedIndex);
             });

Lambda 表达式几乎可以在您想要使用合理简单实现创建委托实例的任何地方发挥作用。

为了提供另一个恰当的例子,假设您想要启动一些线程来处理许多值中的每一个。 (让我们忽略我们正在创建大量线程的事实 - 同样的技术也适用于线程池。)您可以使用类似的方法:

foreach (string url in urls)
{
    // Slight quirk due to variable capture semantics
    string urlCopy = url;
    new Thread(() => FetchUrl(urlCopy)).Start();
}

以强类型方式执行此操作通常很棘手 - 有 ParameterizedThreadStart ,但这不是通用的,所以它变得很繁琐。 在我看来,这非常干净。

For non-expression trees, you can certainly write multi-line lambda expressions. Just this morning I wrote something along the lines of:

 var query = foo.Select(x => {
               string text = x.Value;
               int delimitedIndex = text.IndexOf(' ');
               return int.Parse(text.Substring(0, delimitedIndex);
             });

Lambda expressions can be useful almost anywhere that you want to create delegate instances with reasonably simple implementations.

To provide another case in point, suppose you want to start some threads to do work on each of many values. (Let's ignore the fact that we're creating lots of threads - the same technique works for threadpools too.) You can use something like:

foreach (string url in urls)
{
    // Slight quirk due to variable capture semantics
    string urlCopy = url;
    new Thread(() => FetchUrl(urlCopy)).Start();
}

Doing that in a strongly-typed way normally is tricky - there's ParameterizedThreadStart, but that's not generic, so it becomes fiddly. This is pretty clean IMO.

独孤求败 2024-08-02 05:28:10

谢谢乔恩,

您的多线功能非常受欢迎

x => {
字符串文本 = x.Value;
int delimitedIndex = text.IndexOf(' ');
return int.Parse(text.Substring(0, delimitedIndex);
如果

可能的话,您能否提供更多示例或情况,其中 lambda 表达式可以代替其他编程技术提供很大帮助……只有在可能的情况下,

我认为这会对很多人有所帮助,因为仅了解技术上的东西是不够的,但知道在哪里使用它的实际应用以及它在特定情况下如何提供帮助非常重要。

Thanks Jon,

Your Multi line function is very well received

x => {
string text = x.Value;
int delimitedIndex = text.IndexOf(' ');
return int.Parse(text.Substring(0, delimitedIndex);
}

if possible can you provide some more examples or situation where lambda expression can be of great help in place of other programming techniques...only if possible

I think this will help so many people because knowing things technically is not sufficient but where to use it practically and how it will help in particular situation is very important.

格子衫的從容 2024-08-02 05:28:10

我经常使用 lambda 作为事件处理程序,例如:

button.Click += (sender, e) => DoSomething();

我觉得它创建了一个非常干净的语法,有时闭包语义对于处理事件很有用。

I've used lambdas quite a bit as event handlers, e.g:

button.Click += (sender, e) => DoSomething();

I feel that it creates a very clean syntax and occasionally the closure semantics can be useful for handling events.

全部不再 2024-08-02 05:28:10

.NET 4 的新任务并行库广泛使用它。 例如,如果您想并行运行一段代码,您可以编写:

 Parallel.For(1, 10, i =>
 {
   // do work
 });

在我看来,这比仅仅向其传递一个方法要好得多,如下所示:

 Parallel.For(1, 10, SomeMethodWithIntAsParam); 

The new Task Parallel Library of .NET 4 uses it extensively. For example, if you want to run a block of code in parallel, you can write:

 Parallel.For(1, 10, i =>
 {
   // do work
 });

This works much nicer than just passing a method to it in my opinion, like this:

 Parallel.For(1, 10, SomeMethodWithIntAsParam); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文