C# 如何将Func正确添加到Linq?
我有两段代码。我想知道它们是否相等C# 如何将Func正确添加到Linq?,c#,linq,C#,Linq,我有两段代码。我想知道它们是否相等 properties = type.GetProperties() .Where(IsNeverSerializedProperty) .ToArray(); private static bool IsNeverSerializedProperty(PropertyInfo p) { return p.Name.Contains("Password") ||
properties = type.GetProperties()
.Where(IsNeverSerializedProperty)
.ToArray();
private static bool IsNeverSerializedProperty(PropertyInfo p)
{
return p.Name.Contains("Password") ||
p.GetCustomAttributes(typeof(EncryptedConfigurationItemAttribute), false).Any();
}
它是否等同于以下代码
properties = type.GetProperties()
.Where(p => p.Name.Contains("Password"))
.Where(p => p.GetCustomAttributes(typeof(EncryptedConfigurationItemAttribute), true).Any()))
.ToArray();
如果它们不相等,我会犯什么错误?它们不相等
IsNeverSerializedProperty检查属性名是否包含密码或是否具有EncryptedConfigurationItemAttribute属性,而第二个查询检查属性名是否包含密码,属性是否具有EncryptedConfigurationItemAttribute属性。将代码简化为其基本形式,您的第一个代码片段就是以下形式
list.Where(p => NameContainsPassword(p) || HasEncryptedConfigurationItemAttribute(p))
list
.Where(p => NameContainsPassword(p))
.Where(p => HasEncryptedConfigurationItemAttribute(p))
我内联了你的IsNeverSerializedProperty函数
第二个函数是形式
list.Where(p => NameContainsPassword(p) || HasEncryptedConfigurationItemAttribute(p))
list
.Where(p => NameContainsPassword(p))
.Where(p => HasEncryptedConfigurationItemAttribute(p))
它首先过滤NameContainesPasswordp持有的所有项目,然后从中过滤HasEncryptedConfigurationItemAttribute持有的所有项目,因此这相当于
list.Where(p => NameContainsPassword(p) && HasEncryptedConfigurationItemAttribute(p))
请注意,逻辑运算符不同| | vs&。它们不相等,因为您为GetCustomAttributes提供了不同的参数。但是,为什么不在调试器中尝试一下,看看它们是否正确?假设第二个示例第3行的x只是一个输入错误,它们仍然是不等价的:第二个示例过滤名称包含密码且具有EncryptedConfigurationItemAttribute的所有属性。第一个筛选条件为true的属性。将两个Where方法的谓词放入一个Where方法不是更有效吗:。Wherep=>p.Name.Contains…&&p、 GetCustomerAttributes…,所以我需要在IsNeverSerializedProperty中添加&&而不是| |?是的,应该这样做。