最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - ASP.NET Multiple Task Responses Store In the List of 2 Columns - Stack Overflow

programmeradmin1浏览0评论

I am new to C# and I have this code below making multiple API calls. This code works fine as I can see the listResults has the responses from every call.

List<string> listResults = new();
var listIDs = new List<string>
{
    "ID1",
    "ID2",
    "ID3"
};

string baseURL = $"https://API_URL/id=";
var postTasks = listIDs.Select(p => client.GetStringAsync(baseURL + p));
var posts = await System.Threading.Tasks.Task.WhenAll(postTasks);
foreach (var postContent in posts)
{
    listResults.Add(postContent);
    Debug.WriteLine(postContent);
}

Now I want to store the response string in the list of 2 columns: 1st column is the ID and 2nd column is the response string.

So I have this response model:

public class ItemResponseJsonModel
{
    public string ID { get; set; }
    public string ResponseJSON { get; set; }
}

Then I tried to implement list with model in the code below, but this is where I got stuck how to get the ID added in the first column in listResults for each response.

List<ItemResponseJsonModel> listResults = new();
var listIDs = new List<string>
{
    "ID1",
    "ID2",
    "ID3"
};

string baseURL = $"https://API_URL/id=";
var postTasks = listIDs.Select(p => client.GetStringAsync(baseURL + p));
var posts = await System.Threading.Tasks.Task.WhenAll(postTasks);
foreach (var postContent in posts)
{
    listResults.Add(postContent);  // This is where the error will say cannot convert string to ItemResponseJsonModel.
    Debug.WriteLine(postContent);
}

I want the final listResults looks like below where 1st column is the ID and the 2nd column is the response string.

listResults {
    { ID = "ID1", ResponseJSON = "ResponseJSON" },
    { ID = "ID2", ResponseJSON = "ResponseJSON" },
    { ID = "ID3", ResponseJSON = "ResponseJSON" },
}

How can I accomplish that? Can I store it in the Dictionary<string, string>?

I am new to C# and I have this code below making multiple API calls. This code works fine as I can see the listResults has the responses from every call.

List<string> listResults = new();
var listIDs = new List<string>
{
    "ID1",
    "ID2",
    "ID3"
};

string baseURL = $"https://API_URL/id=";
var postTasks = listIDs.Select(p => client.GetStringAsync(baseURL + p));
var posts = await System.Threading.Tasks.Task.WhenAll(postTasks);
foreach (var postContent in posts)
{
    listResults.Add(postContent);
    Debug.WriteLine(postContent);
}

Now I want to store the response string in the list of 2 columns: 1st column is the ID and 2nd column is the response string.

So I have this response model:

public class ItemResponseJsonModel
{
    public string ID { get; set; }
    public string ResponseJSON { get; set; }
}

Then I tried to implement list with model in the code below, but this is where I got stuck how to get the ID added in the first column in listResults for each response.

List<ItemResponseJsonModel> listResults = new();
var listIDs = new List<string>
{
    "ID1",
    "ID2",
    "ID3"
};

string baseURL = $"https://API_URL/id=";
var postTasks = listIDs.Select(p => client.GetStringAsync(baseURL + p));
var posts = await System.Threading.Tasks.Task.WhenAll(postTasks);
foreach (var postContent in posts)
{
    listResults.Add(postContent);  // This is where the error will say cannot convert string to ItemResponseJsonModel.
    Debug.WriteLine(postContent);
}

I want the final listResults looks like below where 1st column is the ID and the 2nd column is the response string.

listResults {
    { ID = "ID1", ResponseJSON = "ResponseJSON" },
    { ID = "ID2", ResponseJSON = "ResponseJSON" },
    { ID = "ID3", ResponseJSON = "ResponseJSON" },
}

How can I accomplish that? Can I store it in the Dictionary<string, string>?

Share Improve this question edited yesterday Milacay asked 2 days ago MilacayMilacay 1,5099 gold badges36 silver badges62 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

If you want to add an object to a list of a specific type, you have to get or generate an instance of that type. e.g. new ItemResponseJsonModel(). If you want to add ItemResponseJsonModel to a List<ItemResponseJsonModel> you have to create it and then add it. C# offers syntactic sugar to make it easy for you. e.g. .Select(x => new ItemResponseJsonModel()) You can create the desired object on the fly within the linq select method. I have tried to make as few changes as possible to your code:

using System;
using System.Diagnostics;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
                    
public class Program
{
    public static HttpClient client;
    public static async void Main()
    {
        List<ItemResponseJsonModel> listResults = new();
        var listIDs = new List<string>
        {
            "ID1",
            "ID2",
            "ID3"
        };

        string baseURL = $"https://API_URL/id=";
        var postTasks = listIDs
            .Select(async p => new ItemResponseJsonModel { ID = p, ResponseJSON = await client.GetStringAsync(baseURL + p) });
        var posts = await System.Threading.Tasks.Task.WhenAll(postTasks);
        foreach (var postContent in posts)
        {
            listResults.Add(postContent); 
            Debug.WriteLine(postContent);
        }
    }
}

public class ItemResponseJsonModel
{
    public string ID { get; set; }
    public string ResponseJSON { get; set; }
}

What it's doing:

var postTasks = listIDs
    .Select(async p => new ItemResponseJsonModel { ID = p, ResponseJSON = await client.GetStringAsync(baseURL + p) });

This line is:

  • Looping over each ID in listIDs

  • For each ID (p), it is asynchronously calling an HTTP GET request using client.GetStringAsync() to get a response from the API.

  • Once the response is retrieved, it is creating an instance on the fly of type ItemResponseJsonModel with:

    • ID set to p (the current ID)

    • ResponseJSON set to the actual JSON string returned by the API.

  • It produces a collection of Task<ItemResponseJsonModel> (because of the async lambda).

The result, postTasks, is an IEnumerable<Task<ItemResponseJsonModel>> – so a list of tasks that, when awaited, will give you the response models.

发布评论

评论列表(0)

  1. 暂无评论