在where子句中使用变量的LINQ查询

时间:2012-03-16 23:37:33

标签: linq c#-4.0

我已经在这几个小时,倾注了几个相似的问题。如何使此代码生效?

public void DoSomething(List<TheObj> objs, string lnameStr)
    {
        var pQuery = (from o in objs
                      where o.Lname.Contains(lnameStr)
                      select o).ToList();

        foreach (var theObj in pQuery)
        {
            Trace.WriteLine(theObj.Fname);
        }
    }

由于

1 个答案:

答案 0 :(得分:2)

public void DoSomething(List<TheObj> objs, string lnameStr)
    {
      if(objs != null && !string.IsNullOrEmpty(lnameStr))   
       {
        var pQuery = (from o in objs
                      where !string.IsNullOrEmpty(p.Lname) && 
                            o.Lname.Contains(lnameStr)
                      select o).ToList();

        foreach (var theObj in pQuery)
        {
            Trace.WriteLine(theObj.Fname);
        }
      }
    }