简体   繁体   English

将字符串数组解析/转换为 int

[英]Parse/convert string array to int

I want to make summations in certain columns, initially I found a referral as follows我想在某些列中进行汇总,最初我找到了一个推荐如下图片1

then because I use one string in one column then I change the array from int to string as follows然后因为我在一列中使用一个字符串,所以我将数组从 int 更改为 string,如下所示

string[,] a = {     
                    {"name song 1", 2},  
                    {"name song 2", 5},  
                    {"name song 3", 8}  
               };

then I run but an error appears然后我运行但出现错误

error CS0029: Cannot implicitly convert type int' to string'错误 CS0029:无法将类型int' to string'

I have tried this Convert string[] to int[] in one line of code using LINQ我已经使用 LINQ 在一行代码中尝试了这个 Convert string[] to int[]

because I was just learning this language I couldn't implement it please help me thanks因为我刚刚学习这种语言我无法实现它请帮助我谢谢

It seems that you want to store key-value pairs, this can be done using a Dictionary.您似乎想要存储键值对,这可以使用字典来完成。 Checkout the following example:查看以下示例:

var scoreBySong = new Dictionary<string, int> {
  {"name song 1", 2},  
  {"name song 2", 5},  
  {"name song 3", 8}  
}

I'd prefer to use dictionary in this case, but it might be handy for you to know as well that you can store values of different types using the object type.在这种情况下,我更喜欢使用字典,但您可能也知道可以使用object类型存储不同类型的值。 Later you'll have to do type conversion to use math operations稍后您必须进行类型转换才能使用数学运算

object[,] a = 
{
    {"name song 1", 2},
    {"name song 2", 5},
    {"name song 3", 8}
};

var sum = 0;

for (int i = 0; i < a.GetLength(0); i++)
{
    sum += Convert.ToInt32(a[i, 1]);
}

Console.WriteLine(sum);

If you are familiar with classes, you could reorganize your multi-dimensional array into single-dimensional, which makes code way more readable.如果您熟悉类,则可以将多维数组重新组织为一维数组,这使代码更具可读性。

This approach is better than the previous one or the one that uses dictionary, since you'll have to modify less code when Song class extends into more properties这种方法比以前的方法或使用字典的方法要好,因为当Song class 扩展到更多属性时,您将不得不修改更少的代码

public class Song
{
    public string Name { get; set; }

    public int Value { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Song[] a =
        {
            new Song() { Name ="name song 1", Value = 2 },
            new Song() { Name ="name song 2", Value = 5 },
            new Song() { Name ="name song 3", Value = 8 },
        };

        var sum = 0;

        for (var i = 0; i < a.Length; i++)
        {
            sum += a[i].Value;
        }

        Console.WriteLine(sum);
    }
}

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

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