[英]LINQ ignoring where if someobject is null
考虑以下功能
public static string UpdateCommand<T>(List<string> Except=null,List<string> Only=null)
{
if (Except != null && Only != null)
{
throw new Exception();
}
List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
if (Except != null)
{
for (int i = properties.Count; i-- > 0; )
{
if (Except.Contains(properties[i].Name)) properties.RemoveAt(i);
}
}
if(Only != null)
{
for (int i = properties.Count; i-- > 0; )
{
if (!Only.Contains(properties[i].Name)) properties.RemoveAt(i);
}
}
//etc...
}
它带有2个可选参数,它们都可以为null或它们中的任何一个都可以具有值,但是其中至少一个应该为null。
我试图找出上述的Linq语法,是否有一种方法可以编写where语句,但是如果要比较的列表为null,则可以忽略where语句?
基本上我正在寻找一种仅使用LINQ编写上述内容的方法。
我不能使用相交或除外,因为它在2种不同类型之间
var result = properties
.Where(p => !(Except ?? Enumerable.Empty<String>()).Any(s => s == p.Name))
.Where(p => Only == null || Only.Any(s => s == p.Name))
.ToArray();
我建议您根本不要在该方法中管理过滤。 相反,您可以这样做:
public static string UpdateCommand<T>(Func<IEnumerable<PropertyInfo>, IEnumerable<PropertyInfo>> filterFunc = null)
{
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties();
if (filterFunc != null)
properties = filterFunc(properties);
...
}
像这样使用它:
UpdateCommand(pis => pis.Where(pi => ...))
这种类型的事情是最近讨论了在这里对可能的C#6.0的功能(项目7)的文章。 当前,如果没有一些变通方法,例如在上一个答案中所示,这实际上是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.