Home > Net >  Add values in list from other API method
Add values in list from other API method

Time:04-27

I have one list and in that list I am adding values based on class. See below for details.

result.ContactList = contactsResult.Item2.Select(x => new PrjContact() { 
                            Id = x.ID, 
                            UserId = x.UserId,
                            Name = xName,
                            Email = x.Email, 
                        }).ToList();

Now I need to call one more API and pass this UserId in that API and get phone number for that user.

Then need to add that phone number in above list in result.ContactList.

I have tried in this way.

foreach (var user in contactsResult.Item2)
{
   UserInfo = API.GetUserDetail(user.UserId);
   result.ContactList.Select(x => new ProjectContactView()
                            {
                                Phone = UserInfo.PhoneNumber
                            });
}

But this is not working.

CodePudding user response:

This doesn't do anything:

result.ContactList.Select(x => new ProjectContactView()
{
    Phone = UserInfo.PhoneNumber
});

Sure, it iterates over result.ContactList and projects it into a new collection. But (1) you don't do anything with that collection and (2) it overwrites every object in that collection with an entirely new object that has only one property set.

For starters, if you want to modify result.ContactList then iterate over that:

foreach (var user in result.ContactList)
{

}

Then if the goal here is to use a property on user to fetch data and update user then just update user:

foreach (var user in result.ContactList)
{
    var userInfo = API.GetUserDetail(user.UserId);
    user.Phone = userInfo.PhoneNumber
}
  • Related