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

发布于 2024-07-17 09:32:11 字数 98 浏览 3 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

瞳孔里扚悲伤 2024-07-24 09:32:11

实际上,您可以非常简单地做到这一点,因为列表有一个 ForEach 方法,并且您可以将 Console.WriteLine 作为方法组传入。 然后,编译器将使用隐式转换将方法组转换为 Action(在本例中为 Action),并从该组中选择最具体的方法,在本例中为 Console.WriteLine (int)

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

  list.ForEach(Console.WriteLine);

也可以使用字符串=)

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

Actually you can do it pretty simple, since the list have a ForEach method and since you can pass in Console.WriteLine as 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):

  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.WriteLine is 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).

跨年 2024-07-24 09:32:11

虽然 List.ForEach 的答案非常好。

我发现 String.Join(字符串分隔符,IEnumerable值)方法更有用。

示例:

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"

备注:

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

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

这应该可以很好地解决这个问题,而对于其他具有数组值的问题来说。 使用同一方法的其他重载,String.Join 方法(字符串,对象[])

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

While the answers with List<T>.ForEach are very good.

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

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.

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.

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[])

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

梦幻之岛 2024-07-24 09:32:11

假设项目适当地覆盖 ToString :(

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

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

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

如果您有任意序列(例如作为 LINQ 表达式的结果),我上面的循环会更灵活,但如果您确实有一个 List 我会说 List.ForEach 是更好的选择。

List.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);

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

顺便说一下,请注意使用 Console.WriteLine 作为方法组。 这比使用 lambda 表达式更简洁,而且实际上稍微更高效(因为委托将只是调用 Console.WriteLine,而不是调用一个方法,该方法又只调用Console.WriteLine)。

Assuming the items override ToString appropriately:

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 foreach part in this case.)

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

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>.ForEach is a better option.

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

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 T is) it will use Console.WriteLine(object).

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

巷子口的你 2024-07-24 09:32:11

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

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

此代码的运行速度显着更快!

上面的代码还使您能够操作 Console.WriteLine,例如执行以下操作:

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

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

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

This code also runs significantly faster!

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

List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.
北斗星光 2024-07-24 09:32:11
Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
甜心小果奶 2024-07-24 09:32:11

我发现这更容易理解:

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

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]);
        }
一袭水袖舞倾城 2024-07-24 09:32:11

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

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

然后您可以连接到数据库并执行数据检索部分并将其保存到列表中,如下所示。

            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")),
                        });
                    }

然后您可以在命令提示符下打印此列表,如下所示。

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

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.

    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);
                        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文