'C# How to store string values in a list outputted from a loop
Q: How can I capture the data within my string list. After it's been looped? Therefore, I can use the list variable elsewhere in my method.
Goal: The output to the console needs to contain the value of what it's holding (i.e. the alphabet letters). The function only runs one time. In my progress...my desired/expect outcome almost-occurs when I loop my list a.k.a my string value within a foreach loop. However, I only want the output data one time...so a for loop is preferable (because it only runs once.)
I believed the simplest way to solve my dilemma is to add another for loop to iterate over the existing list. Then print the index + 1, and the value at that index to find the solution. But I am having issues.
Expected output (only runs once in a loop)
ABC
DEF
GHI
JKL
MNO
Example Code:
var FriendsList = new List<string>();
foreach (var friends in Obj.users)
{
FriendsList.Add(friend.user);
foreach (var i in FriendsList)
{
Trace.WriteLine(i);
}
}
Undesirable output example:
001
001
002
001
002
003
001
002
003
004
001
002
003
004
005
I don't believe this to be a good solution
//Using Linq to itterate over an array
var Arr = new string[4] {"one", "Two", "Three", "Four"};
Trace.WriteLine(Arr.Select((s, i) => $"Item no: {i + 1}, Value: {s}"));
It's wasteful.
I appreciate the help! Please provide examples.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
