3

I want to display the contents of the Array from a label with a comma between each number. num1 - num6 are integer variables converted from textboxes. So Far I have done this.

int[] number = new int [6] {num1, num2, num3, num4, num5, num6};

Array.Sort(number);

lblAnswer3.Text = number.ToString();

The output of this code is: System.Int32[]

I would like the output to be: num1, num2, num3, num4, num5, num6 in ascending order.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Callum Osborn
  • 45
  • 1
  • 2
  • 6

2 Answers2

6

You can easily concat IEnumerables and arrays with string.Join:

lblAnswer3.Text = string.Join(", ", number);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
m0sa
  • 10,712
  • 4
  • 44
  • 91
0

You can do it using Linq:

lblAnswer3.Text = number.OrderBy(x => x).Select(x => x.ToString()).Aggregate((a, b) => a + ", " + b);
Bogdan B
  • 485
  • 5
  • 15
  • 1
    -1. All of that is unnecessary. – John Saunders Oct 17 '14 at 22:57
  • 3
    @JohnSaunders Kind of harsh to down-vote a solution that works, isn't it? Shouldn't we just upvote the solutions that we like the best and down vote ones that either don't work or don't answer the question? – Rufus L Oct 17 '14 at 23:01
  • @RufusL I'm not sure *I* would downvote it, but this solution is over-complicated enough that I could understand it being regarded as "not useful". The `OrderBy` might be required for ascending order though (if they aren't already ordered). – BradleyDotNET Oct 17 '14 at 23:02
  • @RufusL: the purpose of scoring answers is so that future readers are more likely to choose answers with higher scores. I want to make sure future readers are _less_ likely to choose this one. If the OP is concerned about rep points, then the OP can delete the answer and get the two points back. – John Saunders Oct 17 '14 at 23:09
  • @JohnSaunders Fair enough. – Rufus L Oct 17 '14 at 23:12
  • 1
    "the purpose of scoring answers is so that future readers are more likely to choose answers with higher scores" stating the obvious in a condescending tone only makes you look like a jerk. the answer is not wrong. you can argue it's not as efficient but it's an alternative – Bogdan B Oct 17 '14 at 23:13
  • @bb01234: I didn't say it wouldn't work. I mean that if I were doing a code review and saw that code, I'd ask you to change it. If I were your supervisor and saw that code in a code review, I'd _tell_ you to change it. And, BTW, it's _not_ obvious. Many people don't get why we have upvotes and downvotes here, or get the wrong idea about them. – John Saunders Oct 17 '14 at 23:16
  • It IS obvious, and it is explained in the tour and in the site help. Quality of answers is important but when a newbie asks something it is beneficial to be offered alternatives. For example: what if he had an array of doubles and wanted to string.Format them? A simple string.join would not be sufficient. – Bogdan B Oct 17 '14 at 23:25