我想在某些列中进行总结,最初我找到了如下推荐
然后因为我在一列中使用一个字符串,所以我将数组从 int 更改为字符串,如下所示
string[,] a = {
{"name song 1", 2},
{"name song 2", 5},
{"name song 3", 8}
};
然后我运行但出现错误
<块引用>错误 CS0029:无法隐式转换类型 int' to
string'
我试过这个Convert string[] to int[] in one line of code using LINQ
因为我只是在学习这门语言,所以我无法实现它 请帮助我谢谢
答案 0 :(得分:1)
看来你想存储键值对,这可以使用字典来完成。查看以下示例:
var scoreBySong = new Dictionary<string, int> {
{"name song 1", 2},
{"name song 2", 5},
{"name song 3", 8}
}
答案 1 :(得分:0)
在这种情况下,我更喜欢使用字典,但如果您知道可以使用 object
类型存储不同类型的值,可能会很方便。稍后您必须进行类型转换才能使用数学运算
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);
如果你熟悉类,你可以将你的多维数组重新组织成一维数组,这使得代码方式更具可读性。
这种方法比前一种方法或使用字典的方法要好,因为当 Song
类扩展到更多属性时,您将需要修改更少的代码
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);
}
}