Home > Software engineering >  How to loop though and change background color of each item in a list
How to loop though and change background color of each item in a list

Time:05-13

I'm trying to change the Console.BackgroundColor for each item in a list, and am wondering how I would go about doing so.

public static List<string> cardTypeStore = new List<string>();
public static List<int> cardColorStore = new List<int>();

foreach(//loop through both){
  Console.BackgroundColor = //loop through numbers in cardColorStore
  Console.Write(//print out each item in cardTypeStore)
}

CodePudding user response:

Instead of using a foreach loop, you can use a for loop. The benefit of using the for loop is the index, which can be used to access both collections.

for (int i = 0; i < cardTypeStore.Count; i  )
{
    Console.BackgroundColor = cardColorStore[i];
    Console.Write(cardTypeStore[i]);
}

This will require both collections to have the same number of items, otherwise you risk an Index Out of Range Exception.

A better option, if possible, is to use a class to hold your data. If you want to make changes later, this is much easier to maintain.

public class CardData
{
    public string Type { get; set; }
    public int Color { get; set; }
}

Then you create a single list that you can iterate over using for or foreach.

var cardDataList = new List<CardData>();

// ... populate list with data

foreach (var cardData in cardDataList)
{
    Console.BackgroundColor = cardData.Color;
    Console.Write(cardData.Type);
}
  •  Tags:  
  • c#
  • Related