Med*_*dia 5 c# linq generic-collections
当您使用LINQ来定义可枚举集合时,无论是使用LINQ扩展方法还是使用查询运算符,应用程序实际上都不会在执行LINQ扩展方法时构建集合.只有在迭代它时才会枚举该集合.这意味着原始集合中的数据可以在执行LINQ查询和检索查询标识的数据之间进行更改; 您将始终获取最新的数据.
Microsoft Visual C#2013一步一步由John Sharp编写
我写了以下代码:
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<int> res = numbers.FindAll(a => a > 0).Select(b => b).ToList();
numbers.Add(99);
foreach (int item in res)
Console.Write(item + ", ");
Run Code Online (Sandbox Code Playgroud)
以上代码的结果如下所示:
1,2,3,4,5,
为什么会这样?我知道Func,Action和Predicate,但我无法弄清楚这到底是怎么回事.基于上面的定义,代码是不合理的.
除了ToList()创建新系列的最后,你还有另外一个问题.
问题是你根本就没有使用LINQ.
FindAll 不是LINQ扩展方法.
你应该使用Where:
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<int> res = numbers.Where(a => a > 0);
numbers.Add(99);
foreach (int item in res)
Console.Write(item + ", ");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |