2

Something like

char[] a = new char[] { 'a', 'b', 'c', 'd' };<br>
Console.WriteLine(a);

works nicely with C#. If the type of the array is integer this does not work any longer. It has to be coded as

for (int k = 0; k < a.Length; k++) Console.Write(a[k]); Console.WriteLine();

This looks rather lame to me. Is there a more succinct way to do so? For example some way which expands WriteLine(a) in a loop-free way to

WriteLine("{0},{1},{2},...,{a.Length-1}", a[0],a[1],a[2],...,a[a.Length-1]);

Perhaps there is some neat Linq trick?

3
  • I am looking for a substitute in the case that it is /not/ a char[]. Commented Jul 31, 2010 at 11:59
  • From the look of it, no. The OP is looking for a way that'll work with arrays of any (primitive, at least) type. Commented Jul 31, 2010 at 11:59
  • Three reasons to switch to Java: (1) toString(arr) is more idiomatic, (2) it's there since Java 5, released in 2004, (3) your question gets 13 points, gimel's answer 32 points on SO (question 409784). Commented Aug 1, 2010 at 11:58

7 Answers 7

10

How about String.Join ? Beginning with .Net Framework 4, the second argument is an object[]:

String.Join Method (String, Object[])

Concatenates the elements of an object array, using the specified separator between each element.

Trying a snippet in Visual Studio 2010, targeting framework 4:

    int[] a = new int[] {1,2,3,4,5,6,7 };
    Console.WriteLine(String.Join(",", a));

Produces:

1,2,3,4,5,6,7
Sign up to request clarification or add additional context in comments.

Comments

1

The .Aggregate<TSource, TAccumulate>(source, func) is your friend in this case. You can seed it with a StringBuilder and then just chain Appends from there. Most of the member methods on the StringBuilder class return an instance to the StringBuilder you passed in making it great to use in these types of scenarios.

Sample...

var charArray = new[] { 'a', 'b', 'c', 'd' };
var objectArray = new object[] { 'a', "Hello", 1, null };

Console.WriteLine(new string(charArray));
Console.WriteLine(objectArray.Aggregate(
    new StringBuilder(), 
    (sb,v)=>sb.Append(v+" ")));

Result ...

abcd
a Hello 1

Comments

0

it works because of ToString() method. After all there is a loop inside toString() ! For any of your custom classes you can override toString method.

Comments

0

I think you can use something like:

a.ForEach(e=>WriteLine(e))

1 Comment

There are two syntax errors, as far as I see. This works: Array.ForEach(a, e => Console.Write(e)); Console.WriteLine(); Which is not much better than the for-loop.
0

You can use Enumerable.Select and Aggregate

var intArray = new[] { 1, 2, 3, 4 };

Console.WriteLine(intArray.Select(i => i.ToString())
                          .Aggregate((acc, item) => acc + "\n" + item));

This outputs:

1   
2    
3    
4

1 Comment

This solution has one major problem. Since string is immutable type, new instance has to be created for each item of the list and therefore this algorithm has space complexity in O(n^2). You should use StringBuilder instead.
0
Enumerable.Range(0, 100).ToList().ForEach(Console.Write); Console.WriteLine();

The ForEach() method is specific for List<T>, but you can create your own extension method on IEnumerable<T> for this, if you want:

public static class MyExtensions
{
    public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
    {
       foreach (var item in list) action(item);
    } 
}

Now you can do this:

 Enumerable.Range(0, 100).ForEach(Console.Write);

3 Comments

You probably don't need the ToList
@Rup see my edit. If you dont want the ToList(), you need to add your own ForEach extension method on IEnumerable<T>.
Oops, forgot about that - sorry!
0

Confused as to what the OP is asking, since the sample code does two different things. One prints:

123456

The other prints:

1,2,3,4,5,6

If you want the second, use gimel's solution (using string.Join). If you want the first, here's the simplest method, which is easy to read, even for C# newbies, and will work even in C# 1.0:

foreach(object k in a)
    Console.Write(k);

Why over complicate such a simple thing? While this is not "loop-free", it is just as concise as the rest of them. The rest are still loops, they're just hidden by syntax :)

3 Comments

For me gimel's Console.WriteLine(String.Join(",", a)) looks far better then any for or foreach-loop. And that there are also some bits and bytes hidden by the syntax does even yours truly newbie know.
@Johnathan: I guess the point I was making is that this 10 different ways to tie your shoes is little more than academic. Use the simplest and most obvious method available to you, as long as it doesn't make your program long/grotesque, and then everyone will understand your programs.
@Johnathan: Oh, also, I don't mean to bad mouth you, or new programmers :) I just meant it wasn't hidden behind any hocus-pocus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.