Home > Back-end >  Passing IEnumerable as parameter
Passing IEnumerable as parameter

Time:08-30

I have a problem understanding how IEnumerable works in C#.

Background

I'm developing an Azure Function, the purpose of which is to combine data from different API's. I have used an API generator for each of the sources.

Currently I'm trying to make a Post request with one of the generated functions, but I'm having trouble providing data in the correct format for the parameter.

First of all, in the API's Swagger documentation, it says that the function I'm using requires a Request body that looks like this:

[
{
"name": "string",
"address": "string"
"properties": {
  "prop1": "string",
  "prop2": "string",
},
}
]

... and when looking at the function in Visual Studio, function needs parameter type of " IEnumerable<> body ".

What have I tried?

First I thought that I could just create an object and pass it as a parameter. Something like this:

        var newProperties = new ApiProperties()
        {
            Prop1 = "example",
            Prop2 = "example"
        };

        var newApiData = new ApiData()
        {
            Name = "example",
            Address = "example",
            Properties = newProperties,
        };

... and passing newApiData as an parameter to the function.

await api.PostDataAsync(newApiData)

But this does not work because parameter needs to be IEnumerable.

Problem

How can I pass the request body information as an IEnumerable type parameter?

CodePudding user response:

var enumerable = new ApiData[] { newApiData };

That is, you need to pass an IEnumerable (array, list), not a single entry

CodePudding user response:

Instead of directly sending the data, just put the data in an array before sending:

await api.PostDataAsync(new ApiData[] { newApiData });
  • Related