2

I have written a code like following below:

Parallel.ForEach(filteredList, (f) =>
{
    var conditionMatchCount = itm.AsParallel().Max(i =>
        // One point if ID matches
        ((i.ItemID == f.ItemID) ? 1 : 0) +
        // One point if ID and QuantitySold match
        ((i.ItemID == f.ItemID && i.QuantitySold == f.QuantitySold) ? 1 : 0)
    );
    // Item is missing
    if (conditionMatchCount == 0)
    {
        ListToUpdate.Add(f);
        missingList.Add(f);
    }
    // Item quantity is different
    else if (conditionMatchCount == 1)
    {
        ListToUpdate.Add(f);
    }
});

I basically have two lists:

// itm - list whos data comes from DB 
// filteredList => whos data comes from an external source

What I'm trying to achieve with the code above is to compare the two lists

and see which items from filteredList (new one) are not present in "itm" list...

If they are not present in "itm" list, they are added to

missingList.Add(f);

Also any items that have different QuantitySold property different than the one in "itm" list, I add them as well to ListToUpdate;

The error that I'm getting here is on the following line:

else if (conditionMatchCount == 1)
{
    ListToUpdate.Add(f);
}

And it says:

Destination array was not long enough. Check destIndex and length and the array's lower bounds

What am I doing wrong here?

P.S. Guys, both ListToUpdate and Missing list are plain simple lists, is that whats causing the issue here?

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
User987
  • 3,663
  • 15
  • 54
  • 115
  • Possible duplicate of [Destination Array not long enough?](http://stackoverflow.com/questions/10362023/destination-array-not-long-enough) – Equalsk Feb 02 '17 at 16:43

1 Answers1

4

Don't use List<T> with multiple threads. They aren't thread safe.

Consider using a collection from System.Collections.Concurrent.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445