1

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?

aksoco
  • 131
  • 1
  • 13

3 Answers3

0
var enumerable = new ApiData[] { newApiData };

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

Nick Farsi
  • 366
  • 4
  • 19
  • I tried this, but it gives an error "Argument 2: cannot convert from ’Project.Models.ApiData [] to ‘System.Collections.Generic.IEnumerable<>’ ". – aksoco Aug 29 '22 at 12:07
  • change method signature from IEnumerable<> to IEnumerable – Nick Farsi Aug 29 '22 at 12:09
0

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

await api.PostDataAsync(new ApiData[] { newApiData });
Just Shadow
  • 10,860
  • 6
  • 57
  • 75
  • I tried this, but it gives an error "Argument 2: cannot convert from ’Project.Models.ApiData [] to ‘System.Collections.Generic.IEnumerable<>’ ". – aksoco Aug 29 '22 at 12:07
  • @aksoco, can you please also share the signature of the function api.PostDataAsync? – Just Shadow Aug 30 '22 at 07:56
0

Instead of an array, create a list:

await api.PostDataAsync(new List<ApiData>() { newApiData });

The IList interface inherits from an IEnumerable, that's why a list will work.

I believe it will be very interesting for you to study the following answer: https://stackoverflow.com/a/4455507/3231884

Luis Gouveia
  • 8,334
  • 9
  • 46
  • 68