我想从列表中过滤Recon
项目。我想获取所有具有 Transaction
对象的 Recon
对象,其 Transactions< 中的属性
列表。 SrcObjType
等于“13”/
// The model is like this
public partial class Recon
{
public int ReconNum { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
}
public partial class Transaction
{
public long TransactionId { get; set; }
public Nullable<System.DateTime> DocumentDate { get; set; }
public string SrcObjTyp { get; set; }
public virtual Recon Recon { get; set; }
}
// this works for a few items but crashes on large data sets (million rows large)
List<Recon> reconsWithType13Trans = new List<Recon>();
db.Transactions.Where(t => t.SrcObjTyp == "13")
.ToList().ForEach(t => reconsWithType13Trans.Add(t.Recon));
我认为 foreach 正在占用大量内存,然后程序会引发内存不足异常。
我的问题是如何尽可能高效地过滤这些项目。如果可能,不需要太多内存。如果不使用 foreach 来实现这种过滤,还有另一种可能性吗?
最佳答案
试试这个:
List<Recon> reconsWithType13Trans = db.Transactions
.Where(t => t.SrcObjTyp == "13")
.Select(t => t.Recon).ToList();
这不会加载所有 Transaction
s在内存中,只有他们的Recon
.
您还可以使用 IQueryable<Recon>
并利用 EF 中的延迟执行:
var reconsWithType13Trans = db.Transactions
.Where(t => t.SrcObjTyp == "13")
.Select(t => t.Recon);
关于c# - Linq Filtering items with ForEach crashes for large data set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154109/