Code

How to iterate through a DynamoDBList in C#

How to iterate through a DynamoDBList in C#

I have been working on a new project using some Amazon AWS technology stacks. Have been working in C# and trying to connect to a DynamoDB.

In our DynamoDB there came a point we wanted to store a list of objects in a field. And the way C# reads this from DynamoDB is by a DynamoDBList.

I couldn’t find a lot of examples on the web so just wanted to share an example of how to get the DynamoDBList in C# and then iterate through the list.

            AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
            // Set the endpoint URL to local
            clientConfig.ServiceURL = "http://localhost:8000";
            IAmazonDynamoDB _amazonDynamoDB = new AmazonDynamoDBClient(clientConfig);
            Table dynamoTable = Table.LoadTable(_amazonDynamoDB, "TableName", DynamoDBEntryConversion.V2);

            string idToGet = "somePKID";
            Document loadedUser = await dynamoTable.GetItemAsync(idToGet);
            DynamoDBList tempDBList = loadedUser["some_list"].AsDynamoDBList();
            List<Address> companyList = new List<Address>();

            foreach (var item in tempDBList.Entries)
            {
                Address address = new Address();

                address.City = item.AsDocument()["city"].ToString();
                address.StreeNumber = Convert.ToInt32(item.AsDocument()["street_number"]);
                address.ZipCode = item.AsDocument()["zip_code"].ToString();

                companyList.Add(address);
            }

The above example uses the Document Model to access the info from DynamoDB.

In the example above you get your connection to your DynamoDB table first. Then you would get the item using the PK. Then you cast the Document to a DynamoDBList using AsDynamoDBList().

Once you have the list you can iterate through the DyanmoDBList using the Entries field.

Since the fields in this example is a Document you can cast the item with AsDocument() and reference the fields that you need from there.

I hope this helps you in your search if you ever run across this. The .Entries object wasn’t obvious to me at first. But once I figured that out I was able to get this going pretty quickly.

If you have a more efficient way to do this please share below and let me know.

Leave a Reply

Your email address will not be published.