开发者

query a class object using linq

I am trying to query a class object.

My class :

public class Result
{
   public List<Driver>  Drivers { get; set; }
   public List<Vehicle> Vehicles { get; set; }       
}

I have method to which I am passing an object of this class

  public string BuildRequestXML(Result  开发者_JAVA百科input)
     { 
       var driverNames = new List<Name>(); 
       input.Drivers.ForEach(cd => driverNames.Add(cd.Name)); 
     }                                                                                         

I get Object reference not set to instance error @ the 2nd line of code in the above function.

Thanks in advance. BB.


You'll have to debug to find which one it is, but that exception could be because either input or input.Drivers is null. You could even have a null Driver in the Drivers list.

As for your driversName list, you could rewrite that as

var driverNames = input.Drivers.Select(driver => driver.Name).ToList();


I am not exactly sure why you are getting this problem, however, a better approach would be to use a Select 'projection' as follows:

driverNames  = input.Drivers.Select(d => d.Name).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜