How to display list items on console window in C#

后端 未结 7 1286
执笔经年
执笔经年 2020-11-29 00:19

I have a List which contains all databases names. I have to dispaly the items contained in that list in the Console (using Console.WriteLine()). Ho

相关标签:
7条回答
  • 2020-11-29 00:43

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

    0 讨论(0)
  • 2020-11-29 00:43

    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.
    
    0 讨论(0)
  • 2020-11-29 00:44

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

    0 讨论(0)
  • 2020-11-29 00:46

    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

    0 讨论(0)
  • 2020-11-29 00:47
    Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
    
    0 讨论(0)
  • 2020-11-29 00:55

    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);
                            }
    
    0 讨论(0)
提交回复
热议问题