DBSQUARED
DBSQUARED

Reputation: 83

LINQ | ArgumentOutOfRangeException: Index was out of range

for (int i = 0; i < intFeatureIDs.Count; i++) {
    slots_for = slots_for.Where(s => s.featureSlotMapping.Any(fsm => fsm.featureID == intFeatureIDs[i]));
}

Here, intFeatureID.Count is 2. And throws below exception.

Exception:

Message=An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.

Inner Exception 1: ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

If intFeatureIDs.Count == 1, there is no issue.

Also, If I comment out the for loop, and manually run the code twice, it will work...

slots = slots.Where(s => s.featureSlotMapping.Any(fsm => fsm.featureID == intFeatureIDs[1]));
slots = slots.Where(s => s.featureSlotMapping.Any(fsm => fsm.featureID == intFeatureIDs[2]));

Any comments are much appreciated.

Upvotes: 0

Views: 1747

Answers (1)

mjwills
mjwills

Reputation: 23820

I would recommend changing the code to:

for (int i = 0; i < intFeatureIDs.Count; i++) {
    var bob = intFeatureIDs[i];
    slots_for = slots_for.Where(s => s.featureSlotMapping.Any(fsm => fsm.featureID == bob));
}

This fixes the modified closure issue in your code, and potentially insulates your code against other code (not shown in your sample) that may change / reassign intFeatureIDs.

Upvotes: 1

Related Questions