How to display list items on console window in C#

后端 未结 7 1339
执笔经年
执笔经年 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: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.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 I'd say that List.ForEach is a better option.

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

    List integers = new List { 1, 2, 3 };
    List strings = new List { "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 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).

提交回复
热议问题