-2

I want to make summations in certain columns, initially I found a referral as follows picture1

then because I use one string in one column then I change the array from int to string as follows

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'

I have tried this Convert string[] to int[] in one line of code using LINQ

because I was just learning this language I couldn't implement it please help me thanks

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 3
    Array is homogeneous data structure means you can store same types of data in array, In your example you are trying to store int in string array – Rahul Shukla May 20 '21 at 12:44
  • in your demo you can wrap your int numbers in " to make them a string sequence but then you always has to cast or convert it to int – TinoZ May 20 '21 at 12:46
  • You could use an array of value tuples `(string, int)[]`, You can even name them `(string Name, int Value)[]` – juharr May 20 '21 at 12:47

2 Answers2

1

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}  
}

Filburt
  • 17,626
  • 12
  • 64
  • 115
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
0

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. 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

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);
    }
}
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40