-3
string[] names = new string[6]
names[0] = "Person 1";
names[1] = "Person 2";
names[2] = "Person 3";
names[3] = "Person 4";
names[4] = "Person 5";
names[5] = "Person 6";

I have a string array like this. I'm distribute this strings in a 3 group in order with labels like this:

[My Windows Form . . . . . . . . . . . . . . . . [X]]
|GROUP A | GROUP B | GROUP C|
|Person 1 .|. Person 3 .|. Person 5|
|Person 2 .|. Person 4 .|. Person 6|

How can I do that on between 18-23 string arrays and write in 3 Group Boxes?

Can Özkan
  • 27
  • 1
  • 6

1 Answers1

2
string[] names = new string[6];
names[0] = "Person 1";
names[1] = "Person 2";
names[2] = "Person 3";
names[3] = "Person 4";
names[4] = "Person 5";
names[5] = "Person 6";

var result = Enumerable.Range(0, names.Length / 3)
                       .Select(i => new string[] { names[i], names[i+1], names[i+2] })
                       .ToArray();

Here this should create your string[][]

After that using StringBuilder you can build your result:

StringBuilder sb = new StringBuilder();
sb.AppendLine("[My Windows Form. . . . . . . . . . . . . . . . [X]]");
sb.AppendLine("|GROUP A | GROUP B | GROUP C|");

foreach (var item in result)
{
    sb.AppendLine($"|{item[0]}|{item[1]}|{item[2]}");
}

string result = sb.ToString();

Here: Full Example in DotNetFiddle

If you don't have i%3 == 0 items in the names, you can do it like this:

StringBuilder sb = new StringBuilder();
sb.AppendLine("[My Windows Form. . . . . . . . . . . . . . . . [X]]");
sb.AppendLine("|GROUP A | GROUP B | GROUP C|");
for (int i=0;i < names.Length; i++)
{
    if((i+1) % 3 == 0)
    {
        sb.AppendLine($"|{names[i]}|");
    }
    else
    {
        sb.Append($"|{names[i]}");
    }
}

string result = sb.ToString();
mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • I want a person in each group that is not in another group. This code adds the same people to different groups. – Can Özkan Dec 11 '16 at 20:53
  • You can do it using sb.Append() and sb.AppendLine() and looking for i% 3 ==0 without making them in one array. – mybirthname Dec 11 '16 at 21:12