[英]How initializing List that is in class in another C# class to fill the list
我在 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; }
}
我需要用我在另一个列表中的值填充位置,例如:
foreach (var item2 in AreaOfInterest.AreaOfInterests)
{
foreach (var item in transactionInit.Locations)
{
item.City = item2.City;
item.County = item2.County;
}
}
但它永远不会进入第二个 foreach,因为它是空的。 我如何将它初始化为新对象,我尝试的任何方法都不起作用。
如果您尝试将位置添加到位置列表中,您需要创建一个新的位置对象(基于 AreaOfInterests 对象),然后将其添加到位置列表中。
// 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);
}
我相信我明白你的意图。 您可以执行以下操作。
transactionInit.Locations.AddRange(AreaOfInterest.AreaOfInterests
.Select(x=> new Location
{
City = x.City,
County=x.County
});
在上面的代码中,您迭代AreaOfInterest.AreaOfInterests
以创建Location
实例并使用List.AddRange(IEnumerable<T>)
将它们添加到transactionInit
的Locations
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.