考虑以下函数
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 语句,但如果要比较的列表为空,则忽略该 where 语句?
基本上我正在寻找一种仅使用 LINQ 编写上述内容的方法。
我不能使用 Intersect 或 Except,因为它介于 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();
关于c# - LINQ 忽略 someobject 为 null 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705917/