简体   繁体   中英

How initializing List that is in class in another C# class to fill the list

I have this class in C#:

   public class Init
       {
          public string First_name { get; set; }.
          public List<LeadLocations> Locations { get; set; }
        }
   public Init()
    {
        this.Locations = new List<LeadLocations>();

    }

 public class LeadLocations
{
    public string City { get; set; }
    public string State { get; set; }
    public string County { get; set; }
}

I need to fill Locations with values that I have in another list like:

        foreach (var item2 in AreaOfInterest.AreaOfInterests)
                {

                    foreach (var item in transactionInit.Locations)
                    {
                        item.City = item2.City;
                        item.County = item2.County;
                    }
           }

but it never goes to second foreach as it is empty. How I can initialize it to new object, anything I try is not working.

If you are trying to add location to a list of locations, you need to create a new location object (based on the AreaOfInterests objects) and then add that to the list of locations.

// Initialize your Locations if its not already initialized. 
//   If its not initialized, you will get Object Reference Not Set to Instance of an Object.
transactionInit.Locations = new List<LeadLocations>();
foreach (var item2 in AreaOfInterest.AreaOfInterests)
{
    // For Each item2, create a new location then insert it in transactionInit.Locations.
    var leadLocation = new LeadLocation() {City = item2.City, County = item2.County};
    transactionInit.Locations.Add(leadLocation);
}

I believe I understood what you are intending to do. You could do the following.


transactionInit.Locations.AddRange(AreaOfInterest.AreaOfInterests
                                                .Select(x=> new Location
                                                        {
                                                          City = x.City,
                                                          County=x.County
                                                        });

In the above code, you are iterating over the AreaOfInterest.AreaOfInterests to create instances of Location and using the List.AddRange(IEnumerable<T>) to add them to the Locations property of transactionInit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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