如何在 C# 中的控制台窗口中显示列表项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/759133/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:06:40  来源:igfitidea点击:

How to display list items on console window in C#

c#console-application

提问by

I have a Listwhich contains all databases names. I have to dispaly the items contained in that list in the Console (using Console.WriteLine()). How can I achieve this?

我有一个List包含所有数据库名称的。我必须在控制台中显示该列表中包含的项目(使用Console.WriteLine())。我怎样才能做到这一点?

回答by Jon Skeet

Assuming the items override ToStringappropriately:

假设项目ToString适当地覆盖:

public void WriteToConsole(IEnumerable items)
{
    foreach (object o in items)
    {
        Console.WriteLine(o);
    }
}

(There'd be no advantage in using generics in this loop - we'd end up calling Console.WriteLine(object)anyway, so it would still box just as it does in the foreachpart in this case.)

(在这个循环中使用泛型没有任何好处——Console.WriteLine(object)无论如何我们最终都会调用,所以它仍然会像foreach在这种情况下的部分那样装箱。)

EDIT: The answers using List<T>.ForEachare very good.

编辑:使用的答案List<T>.ForEach非常好。

My loop above is more flexible in the case where you have an arbitrary sequence (e.g. as the result of a LINQ expression), but if you definitely have a List<T>I'd say that List<T>.ForEachis a better option.

在您有任意序列的情况下(例如作为 LINQ 表达式的结果),我上面的循环更灵活,但如果您肯定有一个,List<T>我会说这List<T>.ForEach是一个更好的选择。

One advantage of List<T>.ForEachis that if you have a concrete list type, it will use the most appropriate overload. For example:

的一个优点List<T>.ForEach是,如果您有一个具体的列表类型,它将使用最合适的重载。例如:

List<int> integers = new List<int> { 1, 2, 3 };
List<string> strings = new List<string> { "a", "b", "c" };

integers.ForEach(Console.WriteLine);
strings.ForEach(Console.WriteLine);

When writing out the integers, this will use Console.WriteLine(int), whereas when writing out the strings it will use Console.WriteLine(string). If no specific overload is available (or if you're just using a generic List<T>and the compiler doesn't know what Tis) it will use Console.WriteLine(object).

写出整数时,这将使用Console.WriteLine(int),而写出字符串时,它将使用Console.WriteLine(string)。如果没有特定的重载可用(或者如果您只是使用泛型List<T>而编译器不知道是什么T),它将使用Console.WriteLine(object).

Note the use of Console.WriteLineas a method group, by the way. This is more concise than using a lambda expression, and actually slightlymore efficient (as the delegate will justbe a call to Console.WriteLine, rather than a call to a method which in turn just calls Console.WriteLine).

Console.WriteLine顺便说一下,请注意作为方法组的使用。这比使用lambda表达式更加简洁,并且实际上稍微更有效(作为代表将刚刚是一个呼叫Console.WriteLine,而不是这又只是调用方法的调用Console.WriteLine)。

回答by CasperT

You can also use List's inbuilt foreach, such as:

您还可以使用 List 的内置 foreach,例如:

List<T>.ForEach(item => Console.Write(item));

This code also runs significantlyfaster!

这段代码的运行速度也明显更快!

The above code also makes you able to manipulate Console.WriteLine, such as doing:

上面的代码也让你能够操作 Console.WriteLine,比如:

List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.

回答by Svish

Actually you can do it pretty simple, since the list have a ForEachmethod and since you can pass in Console.WriteLineas a method group. The compiler will then use an implicit conversion to convert the method group to, in this case, an Action<int>and pick the most specific method from the group, in this case Console.WriteLine(int):

实际上你可以做的很简单,因为列表有一个ForEach方法,因为你可以Console.WriteLine作为一个方法组传入。然后,编译器将使用隐式转换将方法组转换为 anAction<int>并从组中选择最具体的方法,在本例中为Console.WriteLine(int)

  var list = new List<int>(Enumerable.Range(0, 50));

  list.ForEach(Console.WriteLine);

Works with strings too =)

也适用于字符串 =)

To be utterly pedantic (and I'm not suggesting a change to your answer - just commenting for the sake of interest) Console.WriteLineis a method group. The compiler then uses an implicit conversion from the method group to Action<int>, picking the most specific method (Console.WriteLine(int)in this case).

完全迂腐(我不建议改变你的答案——只是为了兴趣而评论)Console.WriteLine是一个方法组。然后编译器使用从方法组到 的隐式转换Action<int>,选择最具体的方法(Console.WriteLine(int)在本例中)。

回答by BlackCoffee

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));

回答by Bhramar

While the answers with List<T>.ForEachare very good.

虽然答案List<T>.ForEach很好。

I found String.Join<T>(string separator, IEnumerable<T> values)method more useful.

我发现String.Join<T>(string separator, IEnumerable<T> values)方法更有用。

Example :

例子 :

List<string> numbersStrLst = new List<string>
            { "One", "Two", "Three","Four","Five"};

Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"

int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"

Remarks :

评论 :

If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.

如果分隔符为null,则使用空字符串 ( String.Empty) 代替。如果 values 的任何成员为null,则使用空字符串代替。

Join(String,?IEnumerable<String>)is a convenience method that lets you concatenate each element in an IEnumerable(Of String)collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.

Join(String,?IEnumerable<String>)是一种方便的方法,可让您连接IEnumerable(Of String)集合中的每个元素,而无需先将元素转换为字符串数组。它对于语言集成查询 (LINQ) 查询表达式特别有用。

This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String,?Object[])

这应该可以很好地解决问题,而对于其他人来说,具有数组值。使用相同方法的其他重载String.Join Method (String,?Object[])

Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

参考:https: //msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

回答by Adola

I found this easier to understand:

我发现这更容易理解:

List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
        for (int i = 0; i < names.Count; i++)
        {
            Console.WriteLine(names[i]);
        }

回答by Chamila Maddumage

Assume that we need to view some data in command prompt which are coming from a database table. First we create a list. Team_Details is my property class.

假设我们需要在命令提示符中查看一些来自数据库表的数据。首先我们创建一个列表。Team_Details 是我的属性类。

    List<Team_Details> teamDetails = new List<Team_Details>();

Then you can connect to the database and do the data retrieving part and save it to the list as follows.

然后就可以连接数据库,进行数据检索部分,保存到列表中,如下所示。

            string connetionString = "Data Source=.;Initial Catalog=your DB name;Integrated Security=True;MultipleActiveResultSets=True";
            using (SqlConnection conn = new SqlConnection(connetionString)){
            string getTeamDetailsQuery = "select * from Team";
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(getTeamDetailsQuery, conn))
                    {
                        SqlDataReader rdr = cmd.ExecuteReader();
                    {
                        teamDetails.Add(new Team_Details
                        {
                            Team_Name = rdr.GetString(rdr.GetOrdinal("Team_Name")),
                            Team_Lead = rdr.GetString(rdr.GetOrdinal("Team_Lead")),
                        });
                    }

Then you can print this list in command prompt as follows.

然后你可以在命令提示符下打印这个列表,如下所示。

foreach (Team_Details i in teamDetails)
                        {
                            Console.WriteLine(i.Team_Name);
                            Console.WriteLine(i.Team_Lead);
                        }