C# 使用 ForEach 循环遍历列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15350363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating through a list with out using ForEach loop
提问by user1527762
I have a list of list of strings:
我有一个字符串列表列表:
var list = new List<string> {"apples","peaches", "mango"};
Is there a way to iterate through the list and display the items in a console window without using foreach loop may be by using lambdas and delegates.
有没有办法遍历列表并在控制台窗口中显示项目而不使用 foreach 循环可能是使用 lambdas 和委托。
I would like to the output to be like below each in a new line:
我希望输出在一个新行中如下所示:
The folowing fruits are available:
apples
peaches
mango
以下水果可供选择:
苹果
桃子
芒果
采纳答案by Tim Schmelter
You can use String.Join
to concatenate all lines:
您可以使用String.Join
连接所有行:
string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);
回答by Philip Kendall
By far the most obvious is the good old-fashioned for
loop:
到目前为止,最明显的是好的老式for
循环:
for (var i = 0; i < list.Count; i++)
{
System.Console.WriteLine("{0}", list[i]);
}
回答by Unicorno Marley
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i])
}
回答by Preet Sangha
I love this particular aspect of linq
我喜欢 linq 的这个特殊方面
list.ForEach(Console.WriteLine);
It's not using a ForEach loop per se as it uses the ForEach actor. But hey it's still an iteration.
它本身不使用 ForEach 循环,因为它使用 ForEach actor。但是,嘿,这仍然是一个迭代。
回答by MarcinJuraszek
You can use List<T>.ForEach
method, which actually is not part of LINQ, but looks like it was:
您可以使用List<T>.ForEach
方法,它实际上不是 LINQ 的一部分,但看起来像:
list.ForEach(i => Console.WriteLine(i));
回答by joce
Well, you could try the following:
好吧,您可以尝试以下操作:
Debug.WriteLine("The folowing fruits are available:");
list.ForEach(f => Debug.WriteLine(f));
It's the very equivalent of a foreach
loop, but not using the foreach
keyword,
它非常相当于一个foreach
循环,但不使用foreach
关键字,
That being said, I don't know why you'd want to avoid a foreach
loop when iterating over a list of objects.
话虽如此,我不知道为什么foreach
在迭代对象列表时要避免循环。
回答by daniele3004
There are three ways to iterate a List:
迭代List的三种方式:
//1 METHOD
foreach (var item in myList)
{
Console.WriteLine("Id is {0}, and description is {1}", item.id, item.description);
}
//2 METHOD
for (int i = 0; i<myList.Count; i++)
{
Console.WriteLine("Id is {0}, and description is {1}", myList[i].id, myMoney[i].description);
}
//3 METHOD lamda style
myList.ForEach(item => Console.WriteLine("id is {0}, and description is {1}", item.id, item.description));