string[] groups;
int groupCount;
double[] grades;
int gradeCount;
因此groups
和grades
位于两个独立的数组中,我需要将它们组合为 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]);
}
我该怎么做?
答案 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));
希望有所帮助,