LINQ和数总和法在C# [英] LINQ and Sum method in C#

查看:109
本文介绍了LINQ和数总和法在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前我问了一个问题而它的链接是:
LINQ和递延评价





我问有关于推迟评价,认为LINQ不和的回答是好。但现在我有下面的代码:

 列表< INT>无=新列表与所述; INT>(){1,2,3,4,5}; 
变种RES2 = no.Sum(一个=>一种*一);
Console.WriteLine(RES2);
no.Add(100);
Console.WriteLine(RES2);



如你所知总和是一个扩展方法,但结果不是我所期望的。谢谢:)



编辑:
我期待以下结果:

  55 
10055

但两者都是55

  55 
55


解决方案

只有返回功能的的IEnumerable< T> 可在LINQ的推迟(因为他们可以在允许推迟一个对象被包裹)。



总和的结果是 INT ,所以它不可能推迟它在任何有意义的方式:

  VAR RES2 = no.Sum(A =>将一* ); 
// RES2现在是为55
Console.WriteLine(RES2)的值的整数;
no.Add(100);

//你怎么期望的整数这里改变它的价值呢?
Console.WriteLine(RES2);

您可以推迟执行(不是真的推迟,但显式调用),通过指定的lambda来例如,一个 Func键< T>

 列表< INT> ;无=新列表与所述; INT>(){1,2,3,4,5}; 
Func键< INT> RES2 =()=> no.Sum(一个=>一种*一);
Console.WriteLine(RES2());
no.Add(100);
Console.WriteLine(RES2());

这应该正确地给 55 10055


Previously I asked a question which its link is:
Linq and deferred evaluation


I asked there about the deferred evaluation that linq does and the answer was okey. but now I have the following code:

List<int> no = new List<int>() { 1, 2, 3, 4, 5 };
var res2 = no.Sum(a => a * a);
Console.WriteLine(res2);
no.Add(100);
Console.WriteLine(res2);

As you know Sum is an extension method, but the result is not what I expect. Thanks :)


Edit: I expect the following result:

55
10055

but both are 55

55
55

解决方案

Only functions that return an IEnumerable<T> can be deferred in Linq (since they can be wrapped in an object that allows deferring).

The result of Sum is an int, so it can't possibly defer it in any meaningful way:

var res2 = no.Sum(a => a * a);
// res2 is now an integer with a value of 55
Console.WriteLine(res2);
no.Add(100);

// how are you expecting an integer to change its value here?
Console.WriteLine(res2);

You can defer the execution (not really defer, but explicitly call it), by assigning the lambda to, for example, a Func<T>:

List<int> no = new List<int>() { 1, 2, 3, 4, 5 };
Func<int> res2 = () => no.Sum(a => a * a);
Console.WriteLine(res2());
no.Add(100);
Console.WriteLine(res2());

This should correctly give 55 and 10055

这篇关于LINQ和数总和法在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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