将字符串中的数字转换为双数组几行代码 c#

convert numbers in string to double array few code lines c#

我的字符串包含三个数字 seperated by comma or by space

例如:"3,3,3" or "3 3 3"

字符串还可以在数字之间或字符串的 start\end 处包含空格。

我要insert them into array.

我做到了:

this.ang[0] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]);
this.ang[1] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]);
this.ang[2] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]);

如何使用更少的代码行将数据插入到数组中?

谢谢!

您尝试使用 Linq:

 String ang = "3,3,3"; 

 double[] result = ang
   .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
   .Select(item => Convert.ToDouble(item))
   .ToArray();

String.Split() method already returns an array, so you could perform your split and use LINQ's Select() 方法将每个值解析为双精度值并将这些值存储在数组中:

// This will store the double value for each of your elements into an array
this.ang = ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                     .Select(x => Convert.ToDouble(x))
                     .ToArray();

如果您不能显式设置 this.ang 数组,则可以将之前的结果存储在一个变量中,并根据需要使用它来设置各个值。

例子

你可以see a working example of this in action here.

已经建议的答案假设您可以重新分配整个数组ang。不行就得通过一个for迭代:

var splitString = ang
    .Trim()
    .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)

for(int i = 0; i < 3; i++)
{
    this.ang[i] = Convert.ToDouble(splitString[i]);
}
var ang = "3,3,3"; // or "3 3 3";
var res = ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => Convert.ToDouble(x))
                    .ToList();