首页 > 解决方案 > How can I add to an existing array/ienumerable collection in a foreach loop

问题描述

In my code I have a list of IDs which I am cycling through in a foreach loop.

The IDs relate to a DB record, and I am trying to retrieve items related to each DB record in to a single array which I can then return in JSON

This is what I have so far but it is only returning the items belonging to the last ID.

List<int> IDs = new List<int>(bomIds.Split(',').Select(int.Parse));
IEnumerable<BOMItemSummary> bomItemArray = Enumerable.Empty<BOMItemSummary>();
foreach (var value in IDs)
{


    BOM bom = db.BOMs.Find(value);
    if (bom != null)
    {
        // Got project, get spec items

        bomItemArray = bom.BOMLineItems.Select(bomItem => new BOMItemSummary
        {
            bomItem = bomItem,
            //partNumber = (bomItem.ProductLink.SupplierProductCode != null) ? bomItem.ProductLink.SupplierProductCode : ""
        });


    }
}
jsonResult = Json(new
{
    apiStatus = Utils.Json.JSON_returnStatusSuccess,
    //bomTotal = (bom.BOMValue.HasValue ? bom.BOMValue.Value.ToString("0.00") : "0.00"),
    bomItemArray = bomItemArray,
}, JsonRequestBehavior.AllowGet);

After this I need to select distinct values where the product is the same, but combine the quantities, so the solution should allow for this

标签: c#asp.netasp.net-mvc

解决方案


为什么使用IEnumerable<>?这是微不足道的List.AddRange

List<BOMItemSummary> bomItems = new List<BOMItemSummary>();
...

var bomItemsForId = bom.BOMLineItems.Select(bomItem => new BOMItemSummary
{
    ...
});
bomItems.AddRange(bomItemsForId);

推荐阅读