0
public IEnumerable<ComputedData> Compute (IEnumerable<DataSet> data, IEnumerable<Variations> variationData)
{
   // I need to create one ComputedData instance for each item inside the IEnumerable<DataSet> data 

   // DataSet has properties:  int ID, int Valu1, int Value2
   // ComputedData has properties: int ID, int Result, int Variation

   // variationData has properties: int ID, int Variation

   var computedDate = data.Select (i => new ComputedData ()
            {
                ID = i.ID,
                Result = i.value1 + i.value2
            });

   // ISSUE is here

   foreach (var item in computedDate )
   {
       var id = item.ID;
       // I need to find the corresponding element 
       // (with same ID) on IEnumerable<Variations> variationData
       // and assign item.Variation = 
       // But getting Possible Multiple Enumeration warning
       // and item.Variation become zero always !
   }
}

Issue is the use of foreach loop. Is there any other way to solve this issue. Even though the code is working, item.Variation is always zero. That shouldn't be the case. Any suggestions ?

SomeBody
  • 7,515
  • 2
  • 17
  • 33
dragon123
  • 303
  • 1
  • 3
  • 13
  • 2
    I'd recommend to use `ToDictionary` instead of `ToList` since you need to find element by id. It will reduce complexity from n^2 to n – JL0PD Oct 26 '21 at 07:14
  • 1
    @JL0PD: But he needs to return `IEnumerable` – Tim Schmelter Oct 26 '21 at 07:18
  • 2
    Providing two or three example values for both sources and the expected result collection would extremely help to find the desired solution. – Oliver Oct 26 '21 at 07:44

1 Answers1

0

The warning is to ensure that every time you iterate through the items in computeDate you don't re-execute this:

var computedDate = data.Select(i => new ComputedData()
{
    ID = i.ID,
    Result = i.value1 + i.value2
}).

which could, in turn, re-execute whatever method produced IEnumerable<DataSet> data.

There are few ways to deal with that. An easy one is to add this:

var computedDate = data.Select(i => new ComputedData()
{
    ID = i.ID,
    Result = i.value1 + i.value2
}).ToArray(); // <---- Add this

After this line of code enumerates the items in data the results are stored in an array, which means you can safely enumerate it again and again without executing this Select or anything else unexpected.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62