How do I iterate through a C# class and append values to a string builder?

hi guys
how do I iterate through a c# class e.g. Basket.cs and append the values to a string builder

this is what I have tried

public async Task<string> AddToBasketAsync(Basket basket)
    {
        var s = JsonConvert.SerializeObject(basket);
        s = s.Replace("\"", "");    // This gets rid of all the "\   and leaves only the values enclosed in brackets

    var splitFunction = s.Split(":");

then I have tried to iterate through the s variable and append the values to the StringBuilder class. I know this is a cumbersome way of doing things, hence why I am asking for a better way.

Basically I am trying to get something like this (The values separated by comma)

        string basketValues = basket.Username + "," + basket.ProductID + "," + basket.ProductID + "," + basket.Quantity + ",".ToString();

Thanks

This is perfectly valid. You’d need to ToString the non-string variables but it will work fine.

The other option would be to use String.Format

string basketValues = String.Format("{1},{2},{3},{4}",  basket.Username, basket.ProductID, basket.ProductID, basket.Quantity);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.