gpt4 book ai didi

c# - 为什么 StringComparison.InvariantCultureIgnoreCase 在 where 子句中抛出异常

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:10 24 4
gpt4 key购买 nike

我正在尝试如下所示进行字符串同情:

var nDetails = listOfServiceUrls.Where(x => String.Equals(x.Description,  
serviceName,StringComparison.InvariantCultureIgnoreCase));

但是得到异常,

System.ArgumentException: Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'

如果我删除 where 子句它就可以正常工作!!

 var nDetails = listOfServiceUrls.Where(x => String.Equals(x.Description,serviceName));

最佳答案

您必须使用 Entity Framework 或类似技术,它们实际上需要解释作为参数提供给 Where 的表达式方法。它只会翻译一小部分基类库(标准 .NET 库)方法及其重载。

将光标悬停在您的 listOfServiceUrls 上代码编辑器中的变量并查看它是什么类型。我的钱是因为它是 IQueryable<string> (与 IEnumerable<string> 相对)。

EF 似乎确实对实例 Equals(string, StringComparison) 进行了翻译System.String 上的方法, 因此您可以按如下方式重写代码:

var nDetails = listOfServiceUrls.Where(
x => x.Description.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));

与 .NET 不同,您不会看到 NullReferenceException如果集合中的任何字符串恰好是 NULL - 因为谓词将由 SQL Server 而不是 .NET 运行时执行。

关于c# - 为什么 StringComparison.InvariantCultureIgnoreCase 在 where 子句中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272308/

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