遍历集合并 .Add

Iterate through collections and .Add

我正在尝试将 foreach 循环数据集合存储在循环外以备后用。

考虑以下 foreach 循环。

IList<DetailViewModel> storeAllLoopItems = new List<DetailViewModel>();

foreach (var item in _listOfItems)
{
   var items =
   (from a in context.Employee
       join b in context.Orders on a.Id equals b.Id
       join d in context.Notes on a.Id equals d.Id                            
       where a.Id == item.id
       select new DetailViewModel
       {
         Name = b.LegalName,
         Abbrev = c.Abbrev,
         TaxAmount = a.Amount,
       }).ToList();

      storeAllLoopItems.Add(items); //<<<ERROR
}

错误:

The best overloaded method match for 'System.Collections.Generic.List.Add(DetailViewModel)' has some invalid arguments

cannot convert from 'System.Collections.Generic.List' to 'DetailViewModel'

Add 方法用于添加单个值。您将需要手动将项目添加到列表中,因为 IList 接口没有 AddRange 方法。或者将定义更改为具有 AddRange 方法的 List<DetailValueModel>

另外,.ToList() 不是必需的,会浪费内存。