I'm having an issue with LINQ in C# and this issue has come about multiple times. The problem is around the lambda function that I'm selecting times out of a list or using it for an evaluation to return that item back.
The scenario is I have where I have a List of objects that I have defined and I'm wanting to search through properties of these objects, which some of these properties are Lists. So they are a list of objects, with lists in them, where I need to return the inner list item.
In the code sample as you can see I've got this inside of a parallel for each. I'm only including the line that is being effected. So if I take out the boolean evaluation ( y=> y.ProductName ) this works with no problems. This isn't the first time that this kind of an issue has happened, where something inside of the lambda itself has caused some kind of Field Access Exception, through when evaluating and putting in the string itself it works.
Here is the exception itself:
System.FieldAccessException: Attempt by method '<>x+<>c__DisplayClass0_0.<<>m0>b__1(FinanceService.Models.BusinessRules.Calculations.BenefitCalculatedModel)' to access field 'FinanceService.Excel.Helper.InvoiceHelper+<>c__DisplayClass2_1.CS$<>8__locals1' failed. at <>x.<>c__DisplayClass0_0.<<>m0>b__1(BenefitCalculatedModel y) at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
Oddly enough this doesn't throw an error, when wrapped around a try-catch block, with it catching an Exception object type. I've only been able to find this when evaluating the code when in debug mode.
Has anyone else run into this kind of problem, with Linq functions? Is this a bug with the way I'm coding something or is this a problem with .Net for some odd reason?
The solution/workaround to this problem is just to do another parallel foreach loop and write out the evaluations directly to find it, instead of just using lambdas.
Writing this currently on a Windows 10 box using .Net Framework v4.6.1
Oddly enough this is some how "consistent" depending on the string value or something around that. In other cases if I said look for x=="ABC" will work but x==variable does not work though variable=="ABC" returns a true statement, so either one should work.
Verified that all the variables are publicly accessible.
bool category = false;
//ProductCategory is a string
//ProductName is a string
//y in this case is a string, where x is an object
Parallel.ForEach(_calculatedGroup, b =>
{
List<string> charges = b.Charges.Values.SelectMany(x => x.Select(y => category ? y.ProductCategory : y.ProductName)).Distinct().ToList();
});
Should be returning consistently a list of distinct strings provided in either ProductCategory or ProductName using Linq functions