c# - 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
解决方案
为什么使用IEnumerable<>
?这是微不足道的List.AddRange
:
List<BOMItemSummary> bomItems = new List<BOMItemSummary>();
...
var bomItemsForId = bom.BOMLineItems.Select(bomItem => new BOMItemSummary
{
...
});
bomItems.AddRange(bomItemsForId);
推荐阅读
- javascript - 如何将输入提交的文本链接到 javascript 代码
- swift - 视图之间的 GeometryReader 转换最初会导致 onAppear 触发器
- android - 即使我已确认购买,Google 也会对 3 天内购买的所有订阅进行退款
- sql - 查询选择计数返回比实数更多
- javascript - 在jquery中将撇号值设置为#id
- c - C语言抛硬币代码解读
- react-native - 如何在 React Native 中使用复选框实现多选下拉菜单
- swift - 如何从子视图更新核心数据实体?
- android - Material Design TextInput 更改标签和助手大小
- mysql - Mysql SQL 语法按 [asc|desc] 分组?