Home > other >  C# How to store string values in a list outputted from a loop
C# How to store string values in a list outputted from a loop

Time:02-12

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.

CodePudding user response:

Each time you read a value inside Obj you print the whole new List FriendsList and that's not what you are expecting...

Capturing datas in this way is correct but not the way you wanna print them, you can simply capture them and print friend object values.

var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
 Console.WriteLine("{0}: {1}", friend, friend.user);
}

Otherwise you can use this function after the foreach loop

var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
}

FrindsList.ForEach(Console.WriteLine);
  • Related