Reputation: 564
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.
Upvotes: 0
Views: 380
Reputation: 18155
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
.
Upvotes: 0
Reputation: 11364
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);
}
Upvotes: 1