简体   繁体   English

如何将来自不同数组的两个独立对象转换为一个字符串?

[英]How convert two separate objects from separate arrays into one string?

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

So the groups and grades are in two separate arrays and I need to combine them as one string and add them to a new array.所以groupsgrades在两个单独的数组中,我需要将它们组合为一个string并将它们添加到一个新数组中。

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]);
}

How do i do it ?我该怎么做 ?

C# 6.0 string interpolation (please, notice $ before the string): C# 6.0字符串插值(请注意字符串前的$ ):

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

Another possibility is Linq (in order to output the entire collection in one go ):另一种可能性是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)); 

You forgot string.Format()你忘了string.Format()

It should be,它应该是,

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

Hope helps,希望有所帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM