'How to loop though and change background color of each item in a list [closed]
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)
}
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hijinxbassist |