我正在尝试包含第二个foreach循环来从对象中的列表中提取值,但是我在尝试执行此操作时遇到了问题。
这是代码
private List<Opportunity> CreateOpportunities(Basket basket)
{
var opps = new List<Opportunity>();
foreach (var orderLine in basket.OrderLines)
{
opps.Add(new Opportunity()
**{**
DelegateList = new Delegates
{
foreach (var delegates in orderLine.DelegatesList)
{
FirstName = delegates.FirstName,
LastName = delegates.LastName,
Email = delegates.Email
}
},
CourseId = new CourseBooking
{
Id = orderLine.CourseId
},
Quantity = orderLine.Quantity,
EventId = new EventBooking
{
Id = orderLine.EventId
},
EventItemDecimalPrice = orderLine.Price,
TaxType = new TaxType
{
Id = 1,
Name = "UK VAT",
Rate = orderLine.VatRate
},
RegionCode = orderLine.RegionId
});
}
return opps;
}
我需要实现的是foreach在每个orderLine中循环然后在该orderLine中有一个列表类和一个foreach循环遍历这个,拉出值并声明FirstName,LastName和Email
目前它不会让我创造foreach并获得警告说它期望一个;或者在foreach之前。 任何帮助都会很棒。
编辑:委托构造函数:
public class Delegates
{
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
编辑:机会(DelegateList类)
public class Opportunity
{
[JsonProperty("event")]
public EventBooking EventId { get; set; }
[JsonProperty("course")]
public CourseBooking CourseId { get; set; }
public int Quantity { get; set; }
/// <summary>
/// This is the price per person, NOT the total of the opportunity
/// </summary>
[JsonProperty("price")]
public decimal EventItemDecimalPrice { get; set; }
[JsonProperty("tax_type")]
public TaxType TaxType { get; set; }
[JsonIgnore]
public string RegionCode { get; set; }
[JsonProperty("delegates")]
public List<Delegates> DelegateList { get; set; }
}
答案 0 :(得分:2)
我认为问题是你在对象初始化中放置一个for-each
循环。在初始化for-each
之前,您应该移动内部DelegateList
循环。像 -
foreach (var orderLine in basket.OrderLines)
{
var firstName;
var lastName;
var email;
List<DelegateList> delegates = new List<DelegateList>();
foreach (var delegates in orderLine.DelegatesList)
{
delegates.Add(new Delegates{firstName = delegates.FirstName,lastName = delegates.LastName,email = delegates.Email});
}
opps.Add(new Opportunity()
{//...
然后使用内部循环中填充的List初始化DelegateList
-
DelegateList = delegates;
答案 1 :(得分:1)
使用Linq的选择:
opps.Add(new Opportunity()
{
DelegateList = orderLine.DelegatesList
.Select(orderLineDelegate => new Delegates
{
FirstName = orderLineDelegate.FirstName,
LastName = orderLineDelegate.LastName,
Email = orderLineDelegate.Email
})
.ToList(),
CourseId = ...