Linq statement crashing (no exception) on 2nd method call instantiate object
I have a method which instantiates an object, some of the properties of 开发者_运维百科this object are arrays where i use linq to fetch the data.
private static GrowthYieldStructure CreateGrowthYieldStructure(int timberType, IEnumerable<Tree> trees)
{
var trees1 = trees;
return new GrowthYieldStructure
{
TimberType = timberType,
CurrentDbhList = trees1.Select(x => x.DBH).ToArray(),
CurrentSpeciesList = trees1.Select(x => x.SpeciesNumber).ToArray(),
CurrentTpaList = trees1.Select(x => x.TPA).ToArray(),
CurrentTreeListLength = trees1.Count()
};
}
The first time I call this method it works fine. The second time it will fail with no exception on the second select statement.
-no matter which value its attempting to select
For instance, trees1.Select(x => x.DBH).ToArray()
works, trees1.Select(x => x.SpeciesNumber).ToArray()
crashes.
(I've tried switching the fetching order / making local variable copies / I've checked that values exist and they do, nothing out of the ordinary / using try/catch (no exp caught))
Edit: I made more local variables to store the IEnumerable; still fails
If I only have one select statement it will run fine...
-- Edit2: (calling code - could be off going from memory) stands,plots,trees are all IEnumerable (T being Stand,Plot,Tree)
foreach (var plot in plots.Where(x => x.StandID.Equals(stands.ID))) {
var plot1 = plot;
var treeList = trees.Where(x => x.PlotID.Equals(plot1.ID));
var growthYieldStructure = CreateGrowthYieldStructure(stands.TimberType, treeList); }
Edit3: Finally saw this error: A first chance exception of type 'System.AccessViolationException' occurred in Unknown Module.
Then finally realized my error-
It was actually the code using after the object creation. I was using arrays to send to a external library since arrays are reference types this worked out they way I suspected. But since I was not copying the arrays and instead creating a new local variable which would have the same memory reference.
This caused the next object init to fail since it wanted to write in the same memory loc..
I just changed the object to use IEnumerable this way i can have the array reference once. Sorry for the confusion.
Any thoughts to why it is crashing?
It might be do to the IEnumerable
being an IQueryable
and it is trying to enumerate more than once.
Try changing the line:
var trees1 = trees;
to
var trees1 = trees.ToList();
that will force the enumeration and trees1
will be a List
instead of the possible IQueryable
精彩评论