Question

I am using this code to populate a list in C# with data from a Web Api that gets data from a csv file

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");

var info = new List<SampleDataGroup>();

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();

    var item = JsonConvert.DeserializeObject<dynamic>(content);

    foreach (var data in item)
    {
        var infoSect = new SampleDataGroup
        (
            (string)data.Id.ToString(),
            (string)data.Name,
            (string)"",
            (string)data.PhotoUrl,
            (string)data.Description
        );
        info.Add(infoSect);
    }
}
else
{
    MessageDialog dlg = new MessageDialog("Error");
    await dlg.ShowAsync();
}

I would like to assign a photo to (string)data.PhotoUrl, depending on its Name.

For example: If the Name is "Car", I would like it to be assigned the PhotoUrl "Assets/Images/car.jpg". If an item in the lists Name is "Boat", assign it's PhotoUrl to "Assets/Images/boat.jpg".

The Images are not included of the CSV file that the web api feeds on.

There will be more than one item in the list with the same Name, but all with the same Name will share the same assigned image.

How do I do this?

Was it helpful?

Solution

What is info in new info? Is it some class of yours? If yes, does it inherit from the SampleDataGroup type you typed your list with? If yes and you are assigning values to it using a constructor, then use

data.PhotoUrl = string.Format("Assets/Images/{0}.jpg", data.Name)

Doing this with if/else as mentioned in comments would be a suicide. IF not now, then surely when you decide to expand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top