C# How to convert a struct type list into a string?

I am doing a game in Unity and need help with converting my struct list into a string. My codes below are put inside a class called, MonsterHandler.

public enum S_STATE
{
    S_IDLE,
    S_PATROL,
    S_ATTACK,
    NONE
}

public struct MONSTERS
{
    public string Name;
    public int Health;
    public int Damage;
    public S_STATE State;
};

public List<MONSTERS> monsterList= new List<MONSTERS>();

void Start()
{
   // add data into the monsterList
   // Debug.Log(monsterList.Count); // print out 5

   Debug.Log(monsterList.ToArray()); //printed out "MonsterHandler + MONSTERS"
   // i want to do something like this
   // "Monster_Zombie, 100, 20, S_IDLE, Monster_Donkey, 80, 30, S_IDLE,  Monster_Chicken, 120 , 10, IDLE,.."
}
}

Is there a way to cast my struct list into a string[], then convert into a string? Or there any other ways

Jon Skeet
people
quotationmark

I'd first rename the types (and enum values) to follow .NET naming conventions and to indicate that the struct represents a single monster. It's unfortunate IMO that mutable structs are common in Unity, but I'll leave that part aside.

I'd next override ToString() in Monster. Assuming you can use C# 6 features, string interpolation makes this really simple.

Finally, to convert a list of monsters to a string, you'll want to use string.Join. The exact nature of the call will depend on what you have available - if you're still targeting .NET 3.5, it's slightly ugly. But you'd end up with something like:

public enum State
{
    None, // Idiomatically value 0 in .NET
    Idle,
    Patrol,
    Attack
}

public struct Monster
{
    public string Name;
    public int Health;
    public int Damage;
    public State State;

    // Adjust this as required
    public override string ToString() =>
        $"Name: {Name}; Health: {Health}; Damage: {Damage}; State: {State}";
}

public List<Monster> monsters = new List<Monster>();

void Start()
{
    Debug.Log(string.Join(", ", monsters.Select(m => m.ToString().ToArray());
}

Note that this is an expensive operation - you probably only want to do it when debugging. (I don't know whether calls to Debug.Log are conditional in Unity.)

In .NET 4 and above, you could just use

Debug.Log(string.Join(", ", monsters));

people

See more on this question at Stackoverflow