Search code examples
c#bloomberg

C# Bloomberg: How to loop through an array, create instrument objects, and add to instruments class


I'm working on using Bloomberg's C# web services code to download investment information.

I'm struggling to figure out the correct way to download multiple instruments at the same time by using a string array. The instrument member of the instruments class is an array of Instrument objects. You must create an individual instrument object for each instrument you are requesting and add each object to the array. However, I'm still fairly new to C# and I'm struggling to find the correct way to add multiple instrument objects to the instruments class. The below code simply returns the last investment in the array since the final line in the loop seems to replace the prior investment object.

Any help is appreciated.

Thanks.

 string[] investments = { "BBG000BHGCD1", "BBG000BB2PW9" };

             Instruments instruments = new Instruments();

             foreach (string inv in investments)
             {
                 Instrument instr = new Instrument();
                 instr.id = inv;
                 instr.yellowkeySpecified = false;
                 instr.typeSpecified = true;
                 instr.type = InstrumentType.BB_GLOBAL;
                 instruments.instrument = new Instrument[] { instr };
             }


             // Submitting request
             SubmitGetActionsRequest req = new SubmitGetActionsRequest();
             req.headers = getActionHeaders;
             req.instruments = instruments;

             submitGetActionsRequestRequest subGetActReqReq = new 
 submitGetActionsRequestRequest(req);

Solution

  • Change your loop to this:

            Instruments instruments = new Instruments();
    
            var myList = new List<Instrument>();
    
            foreach (string inv in investments)
            {
                myList.Add(new Instrument
                {
                    id = inv,
                    yellowkeySpecified = false,
                    typeSpecified = true,
                    type = InstrumentType.BB_GLOBAL
                });
    
            }
    
            instruments.instrument = myList.ToArray();