C#选择查询不修改外部变量 [英] C# Select query not modifying external variable

查看:33
本文介绍了C#选择查询不修改外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含n个元素的类,以及一个返回元素的平方根的属性:

I have a class with n elements, and a property that returns the root sum square of the elements:

public double Length 
{ 
    get 
    { 
        double sum = 0.0; 
        Elements.Select(t => sum += t * t);  
        return Math.Sqrt(sum); 
    } 
}

但是,这不起作用-不管元素的值如何,总和仍为0.0.
为什么这行不通?

However, that doesn't work - no matter the value of the elements, sum remains 0.0.
Why doesn't this work?

注意:我已经以另一种方式实现了它,但是我想了解为什么上面的代码不起作用

Note: I have already implemented it another way, but am looking to understand why the above code does not work

推荐答案

LINQ使用延迟执行选择方法不会立即对所有元素执行lambda,但是返回 IEnumerable< T> ,该代码在执行时会在枚举的每个元素.

LINQ uses deferred execution – the Select Method doesn't execute the lambda for all elements immediately, but returns an IEnumerable<T> which, when executed, performes the lambda on each element as it's enumerated.

还要注意,LINQ用于查询,而不是用于为每个元素执行代码块.您应该编写代码,使lambda中没有语句,只有没有副作用的表达式.尝试计算总和时,可以使用求和方法:

Also note that LINQ is for querying, not for executing a block of code for each element. You should write your code such that there is no statement in the lambda, only a expression that is free of side-effects. You can use the Sum Method when you're trying to calculate a sum:

public double Length 
{ 
    get 
    { 
        double sum = elements.Select(t => t * t).Sum();
        return Math.Sqrt(sum); 
    } 
}

public double Length 
{ 
    get 
    { 
        double sum = elements.Sum(t => t * t);
        return Math.Sqrt(sum); 
    } 
}

这篇关于C#选择查询不修改外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆