gpt4 book ai didi

c# - 按 Contains(variable) 过滤时 LINQ Where 的意外输出

转载 作者:行者123 更新时间:2023-11-30 13:18:49 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com