作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "g";
string[] color = { "greena", "browna", "bluea" };
var query = color.Where(c => c.Contains(s));
Console.WriteLine(query.Count());
s = "a";
query = query.Where(c => c.Contains(s));
Console.WriteLine(query.Count());
Console.ReadKey();
}
}
}
我认为它的输出应该如下,因为当query=color.where(c=>c.contains("g"))
我认为它应该包含 {greena}
,所以当第二次查询运行时 query = query.where(c=>c.contains("a");
然后它只匹配绿色,所以当计数为 1 时:
1
1
但是运行代码后的输出是
1
3
为什么第二次过滤匹配所有元素(即使只有一个包含“g”并且第二次查询应该只查看一个)?
最佳答案
您正被捕获的变量咬伤:
var query = color.Where(c => c.Contains(s));
将 s
提升到一个闭包中,并在执行时读取 s
的值。在这种情况下,这发生在您将 s
重新分配给其他东西之后。
您最终得到的查询是:
var query = color.Where(c => c.Contains(s)).Where(c => c.Contains(s));
而不是你可能期望的:
var query = color.Where(c => c.Contains("g")).Where(c => c.Contains("a"));
这将产生您期望的结果:
string s = "g";
string[] color = { "greena", "browna", "bluea" };
var query = color.Where(c => c.Contains(s));
Console.WriteLine(query.Count());
var b = "a";
query = query.Where(c => c.Contains(b));
Console.WriteLine(query.Count()); // <-- This is where the entire expression is evaluated
关于c# - 按 Contains(variable) 过滤时 LINQ Where 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733573/
我是一名优秀的程序员,十分优秀!