简体   繁体   English

C# 如何将字符串值存储在循环输出的列表中

[英]C# How to store string values in a list outputted from a loop

Q: How can I capture the data within my string list .问:如何捕获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 (ie the alphabet letters).目标:控制台的 output 需要包含它所持有的值(即字母)。 The function only runs one time. function 只运行一次。 In my progress...my desired/expect outcome almost-occurs when I loop my list aka my string value within a foreach loop.在我的进步中......当我在foreach循环中循环我的列表也就是我的字符串值时,我想要/期望的结果几乎发生了。 However, I only want the output data one time...so a for loop is preferable (because it only runs once.)但是,我只想要一次 output 数据......所以最好使用for循环(因为它只运行一次。)

I believed the simplest way to solve my dilemma is to add another for loop to iterate over the existing list.我相信解决我的难题的最简单方法是添加另一个for loop来遍历现有列表。 Then print the index + 1 , and the value at that index to find the solution.然后打印index + 1和该索引处的值以找到解决方案。 But I am having issues.但我有问题。

Expected output (only runs once in a loop)预期 output(只循环运行一次)

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:不受欢迎的 output 示例:

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.请举例说明。

Each time you read a value inside Obj you print the whole new List FriendsList and that's not what you are expecting...每次您在Obj中读取一个值时,您都会打印出全新的 List FriendsList而这不是您所期望的......

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.以这种方式捕获数据是正确的,但不是您想要打印它们的方式,您可以简单地捕获它们并打印friend object 值。

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否则你可以在 foreach 循环之后使用这个 function

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

FrindsList.ForEach(Console.WriteLine);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM