c# - LINQ 忽略 someobject 为 null 的位置

标签 c#

考虑以下函数

 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/

相关文章:

c# - Autofixture:控制创建的 string[] 类型元素的数量

c# - ASP.NET vNext - MissingMethodException : Method not found: Microsoft. CodeAnalysis.Diagnostic> EmitResult.get_Diagnostics()'

c# - 嵌套集合 - 问题,当实体的 namespace 已更改时

c# - 如果不为空则从属性中获取值,否则使用 Linq 获取其他属性

c# - 有没有一种巧妙、有效的方法可以用两个不同的参数调用同一个方法两次?

c# - wpf 打破 Window.Grid

c# - mvc脚手架从数据库中删除原始数据

c# - ServiceStack V4 API 文档缺少响应类型(在列表中)

c# - 制定通用和特定的 stub 方法?

c# - 在我的 nuget 包安装后执行一个操作