C#在List对象中查找对象

时间:2015-09-25 20:07:07

标签: c#

我想要做的是,在列表中找到一个对象

Log q = logs.Find(x => (x.dnsq.queryID.Contains(queryid)));

然而,当我这样做时,我收到此错误

  

x.dnsq.queryID ='x.dnsq.queryID'引发了类型异常   “System.NullReferenceException

Log类看起来像这样

class Log : LogCtrl
{
    public int id { set; get; }
    public string source { set; get; }
    public string destination { set; get; }
    public string protocol { set; get; }
    public double time { set; get; }
    public string info { set; get; }
    public DNSresponse dnsr { set; get; }
    public DNSquery dnsq { set; get; }
}

1 个答案:

答案 0 :(得分:2)

对于日志中的至少一个项,听起来像x或x.dnsq或x.dnsq.queryId为空。您可以在声明中通过执行以下操作来检查:

    Log q = logs.Find(x => (x != null && x.dnsq != null && x.dnsq.queryID != null && x.dnsq.queryID.Contains(queryid)));