如何将两个单独的对象从单独的数组转换为一个字符串

时间:2016-10-11 11:09:43

标签: c#

string[] groups;
int groupCount;
double[] grades;
int gradeCount;

因此groupsgrades位于两个独立的数组中,我需要将它们组合为 one string并将它们添加到新数组中。< / p>

string[] test = new string[groupCount];
for (int i = 0; i < groupCount; i++)
{
   test[i] = ("{0}:   {1}", groups[i], Math.Round(grades[i],2));              
   Console.WriteLine("{0}", test[i]);
}

我该怎么做?

2 个答案:

答案 0 :(得分:3)

C#6.0 字符串插值(请注意字符串前的$):

test[i] = $"{groups[i]}:   {Math.Round(grades[i],2)}"; 

另一种可能性是 Linq (为了在一次中输出整个集合):

string[] groups;
double[] grades;

...

var test = groups
  .Zip(grades, (group, grade) => $"{group}:    {Math.Round(grade, 2)}")
  .ToArray(); // array materialization (if you want just to output you don't need it)

Console.Write(String.Join(Environemnt.NewLine, test)); 

答案 1 :(得分:1)

您忘记了string.Format()

应该是,

string.Format("{0}:   {1}", groups[i], Math.Round(grades[i], 2));

希望有所帮助,