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