Tarupron
Tarupron

Reputation: 548

C# Using String.Format to write data to txt in in a grid format

Currently I'm trying to create a grid of data (maybe grid isn't the right word, will show later) using String.Format, now it would be fine on a normal basis except one of the lines could potentially have any number of lines.

The code currently looks roughly like this:

var TextFormat = "{0,-30} {1,-5} {2,-5} {3,-5} {4,-20}";
Text += String.Format(TextFormat, "Name", "ID", "Rarity", "Attributes", "Tier");
for(int i = 0; i < Items.Count; i++)
{
    var Name = Items[i].Name;
    var ID = Items[i].Id;
    var Rarity = Items[i].Rarity;
    var Attributes = Items[i].Attributes.ToList();
    var Tier = Items[i].Tier;
    Text += String.Format(TextFormat, Name, ID, Rarity, Attributes[0], Tier);
}

Basically Attributes[0] is hardcoded as such just for display purposes to ensure formatting was fine in terms of spacing, but ultimately I'd like to have Attributes print multiple lines, so the output would be like this:

Name      ID     Rarity    Attributes    Tier
Sword     0      Common    Damage +2     0
                           Accuracy +1

Shield    1      Common    Defense +5    0
                           Weight +5

I was hoping to use String.Format for ease of spacing and not having to have a uniform number of spaces in between each one, and I'm having difficulty finding a usage of String.Format that is similar to what I'm looking for.

If it's not possible that's fine, I was just hoping there was a good solution that I'm just not seeing.

Upvotes: 0

Views: 867

Answers (1)

Tyler Lee
Tyler Lee

Reputation: 2785

Perhaps something like this would accomplish your goals? Just adding a loop to go over the rest of the attributes. Starting the loop at i=1 will skip the first entry that you already output.

Also, you should consider the StringBuilder comment added by @DiskJunky above.

var TextFormat = "{0,-30} {1,-5} {2,-5} {3,-5} {4,-20}";
Text += String.Format(TextFormat, "Name", "ID", "Rarity", "Attributes", "Tier");
for(int i = 0; i < Items.Count; i++)
{
    var Name = Items[i].Name;
    var ID = Items[i].Id;
    var Rarity = Items[i].Rarity;
    var Attributes = Items[i].Attributes.ToList();
    var Tier = Items[i].Tier;
    Text += String.Format(TextFormat, Name, ID, Rarity, Attributes[0], Tier);
    for(int i=1; i<Attributes.Count; i++){
        Text += String.Format(TextFormat, "", "", "", Attributes[i], "");
    }
}

Upvotes: 1

Related Questions