繁体   English   中英

使用Lambda表达式(C#)返回对象属性的值

[英]Return the values of an object's properties using lambda expression (C#)

我的最终目标是使用单个lambda查询和反射从类及其属性生成字符串数组( string[] )。

第一个代码块成功生成一个IEnumerable,而第二个则没有。 不同之处在于第二个块尝试过滤出具有空值的属性。 我唯一可以得出的结论是,我第二句的语法不知何故。

不产生错误:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("Anchors"))
        select p.GetValue(this));

产生错误:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("Anchors") & 
                     !string.IsNullOrWhiteSpace(n.GetValue(this).ToString()))
        select p.GetValue(this));

我应该如何修改第二个表达式过滤掉有一个值的属性?

这是课程:

public class DataPoint
{
    public string FI_Comments { get; set; }
    public string FI_DateInspected { get; set; }
    public string FI_Anchors1 { get; set; }
    public string FI_Anchors2 { get; set; }
    public string FI_Anchors3 { get; set; }
    public string FI_BoltsNuts1 { get; set; }
    public string FI_BoltsNuts2 { get; set; }
    public string FI_BoltsNuts3 { get; set; }
    public string FI_Conductors1 { get; set; }
    public string FI_Conductors2 { get; set; }
    public string FI_Conductors3 { get; set; }
    public string FI_Conductors4 { get; set; }
    public string FI_Conductors5 { get; set; }

    public string AnchorsData
    {
        get
        {
            return string.Join("\n", from p in GetType()
                                              .GetProperties()
                                              .Where(n => n.Name.Contains("Anchors"))
                                     select p.GetValue(this, null));
        }
    }

最后,我想通过get操作实现的详细信息-我只希望它返回在属性名称中具有“ Anchors”的所有属性的所有非空值。

谢谢!

  • 要处理get ,将需要查找包含Anchors所有内容。

    • AnchorsData包含Anchors因此必须处理get

      • 要处理get ,将需要查找包含Anchors所有内容。

        • AnchorsData包含Anchors因此必须处理get

          • 要处理get ,将需要查找包含Anchors所有内容。

            • AnchorsData包含Anchors因此必须处理get

              • ...

看到问题了吗? 这就是为什么您会收到堆栈溢出错误的原因。

...(n.GetValue(this).ToString())...

我想这就是问题所在。 获取值后,即使可能为null也尝试调用.ToString() 尝试做类似?.ToString()

你在自欺欺人。 别。 无限递归不好。

return string.Join("\n", from p in GetType()
                                  .GetProperties()
                                  .Where(n => n.Name.Contains("Anchors") 
                                           && n.Name != "AnchorsData")  //<-- Don't call yourself!
                         select p.GetValue(this, null));

这应该跳过递归(无论是否测试null / empty属性都应该发生),并且只返回non-empty:

    return string.Join("\n", from p in GetType()
                                       .GetProperties()
                                       .Where(n => n.Name != "AnchorsData" && n.Name.Contains("Anchors") && !String.IsNullOrEmpty(n.GetValue(this)?.ToString()))
                             select p.GetValue(this));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM