73

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?

miftahulrespati
  • 494
  • 4
  • 16

7 Answers7

99

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

d219
  • 2,707
  • 5
  • 31
  • 36
Svish
  • 152,914
  • 173
  • 462
  • 620
  • 3
    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, picking the most specific method (Console.WriteLine(int) in this case). – Jon Skeet Apr 17 '09 at 06:34
  • Yeah, like I said, "if I got my wording correct" :p Updating the answer (let me know if I got it wrong again!) – Svish Apr 17 '09 at 07:15
  • But how to print a 2D list using this method? – Spero Jun 10 '19 at 11:46
50

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

B Bhatnagar
  • 1,706
  • 4
  • 22
  • 35
  • 1
    This is very useful if you want to put the elements of the list inside another string like: Console.WriteLine($"i can write here {String.Join(", ", list)} and here"); – Icaro Mota May 28 '19 at 13:57
35

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
22

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.
CasperT
  • 3,425
  • 11
  • 41
  • 56
  • *Significantly* faster? That sounds very unlikely to me, as the bottleneck will be the console output rather than looping. – Jon Skeet Apr 17 '09 at 06:23
  • 1
    haha I can take that word out. It is just because List.ForEach is faster because it has only one method call per iteration vs standard foreach which has 2 callvirt IL instruction calls – CasperT Apr 17 '09 at 06:27
  • Yes - it's certainly more efficient, just not significantly. It's always worth bearing in mind where the bottlenecks really are :) You can make the first version even more efficient using Console.Write as a method group, btw... (You can't do that with the second, as you're actually manipulating the parameter.) – Jon Skeet Apr 17 '09 at 06:32
  • Heh, yeah that is a fair claim. I forfeit mine :) – CasperT Apr 17 '09 at 07:01
18
Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
BlackCoffee
  • 375
  • 2
  • 10
  • 2
    This worked best for me as I can prepare my string before sending it to the console, instead of sending one line to the console every time – Mart10 Mar 24 '17 at 15:40
0

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]);
        }
Adola
  • 337
  • 1
  • 16
0

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);
                        }
Chamila Maddumage
  • 3,304
  • 2
  • 32
  • 43