Robin Robin - 1 month ago 6
ASP.NET (C#) Question

Combine results from API into one object

I am creating a simple api consumer application using asp.net mvc web api2 controllers.

The two get requests in my web api controller are as follows:

public async Task<List<User>> GetUsersAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return JsonConvert.DeserializeObject<List<User>>(
await httpClient.GetStringAsync("https://jsonplaceholder.typicode.com/posts")
);
}

}

public async Task<List<UserToDoList>> GetUserToDoListAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return JsonConvert.DeserializeObject<List<UserToDoList>>(
await httpClient.GetStringAsync("http://jsonplaceholder.typicode.com/todos")
);
}

}


This gives me List of two separate objects List of Users & List of User To Do's.

What is the best/fastest way to combine them so that I can show it in a tabular format like:

UserId | Name | Count Of Todo's

Answer

Combine the two calls and returns what you want either on the client side by calling your web apis or creating a new endpoint that merges the data and returns the combined data

using (HttpClient httpClient = new HttpClient()) {
    var users = JsonConvert.DeserializeObject<List<User>>(
                    await httpClient.GetStringAsync("https://jsonplaceholder.typicode.com/posts")
                );
    var todos = JsonConvert.DeserializeObject<List<UserToDoList>>(
            await httpClient.GetStringAsync("http://jsonplaceholder.typicode.com/todos")
        );

    var result = from user in users
                 join todo in todos on user.UserId equals todo.UserId into userTodos
                 select new { UserId = user.UserId, Name = user.Name, CountOfTodos = userTodos.Count() };
}